2016-07-16 40 views
2

我正在使用角,chai,角模,摩卡,業力。測試輸出這樣的錯誤:如何讓這個測試通過摩卡?

Type error

[email protected][native code]

app/main.coffee:30:23 <- app/main.js:23:23

test/main.spec.coffee:59:20 <- test/main.spec.js:18:27

assert = chai.assert 
expect = chai.expect 

describe("The Address Book App",() -> 
    describe("the proper filter",() -> 
    proper = null 
    beforeEach(() -> 
     module("AddressBook") 
     inject(($injector)-> 
     proper = $injector.get("$filter")("proper") 
    ) 
    ) 

    it("should proper case a string",() -> 
     expect(proper("ned stark")).to.equal("Ned Stark") 
    ) 
) 
) 

main.coffee

class AddressBook 
    constructor: -> 
    return [] 

class Proper 
    uppercase: (word) -> 
    word[0].toUpperCase().concat(word.slice(1)) 

    constructor:() -> 
    return (name) -> 
     words = name.toString().split(" ") 
     return words.map(@uppercase).join(" ") 


angular.module('AddressBook', new AddressBook()) 
.filter('proper', [Proper]) 

更新

我覺得一個類的方法 '大寫' 更適合這種情況下,用「main.coffee」中的一點變化就是測試通過。

class AddressBook 
    constructor: -> 
    return [] 

class Proper 
    @uppercase: (word) -> 
    word[0].toUpperCase().concat(word.slice(1)) 

    constructor:() -> 
    return (name) -> 
     words = name.toString().split(" ") 
     return words.map(Proper.uppercase).join(" ") 


angular.module('AddressBook', new AddressBook()) 
.filter('proper', [Proper]) 

但是,如果我真的需要和實例方法,如何使通過測試?

回答

0

這是因爲CoffeeScript處理this關鍵字的方式。在你的構造函數中,你正在返回一個函數,但是在這個函數中訪問變量@uppercase。在這種情況下,您希望this關鍵字(即@)引用正在構建的對象實例。但是,this始終引用調用該函數的對象,這種情況是undefined

爲了解決這個問題,簡單地使用脂肪箭頭,CoffeeScript的將設置this關鍵字預期:

class Proper 
    uppercase: (word) -> 
    word[0].toUpperCase().concat(word.slice(1)) 

    constructor:() -> 
    return (name) => 
     words = name.toString().split(" ") 
     return words.map(@uppercase).join(" ") 
+0

這沒有工作,輸出相同的錯誤 – wilcus