如何让这个测试通过摩卡?

时间:2016-07-16 01:41:57

标签: javascript angularjs coffeescript mocha karma-runner

我正在使用角,chai,angularmocks,摩卡,业力。测试输出此错误:

  

输入错误

     

map @ [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])

但如果我真的需要和实例方法,如何让测试通过?

1 个答案:

答案 0 :(得分: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(" ")