简体   繁体   English

如何在Mocha中通过此测试?

[英]How to make this test pass in Mocha?

I'm using angular, chai, angularmocks, mocha, karma. 我正在使用angular,chai,angularmocks,mocha,karma。 The test output this error: 测试输出此错误:

Type error 类型错误

map@[native code] map @ [本地代码]

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

test/main.spec.coffee:59:20 <- test/main.spec.js:18:27 测试/main.spec.coffee:59:20 <-测试/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 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])

Updated 更新

I think a class method 'uppercase' is more appropriate for this case and with a little change in 'main.coffee' the test pass. 我认为类方法“大写”更适合这种情况,并且在“ 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])

But if i really need and instance method, how to make the test pass? 但是,如果我真的需要实例方法,该如何通过测试?

It's because of the way CoffeeScript handles the this keyword. 这是因为CoffeeScript处理this关键字的方式。 In your constructor, you are returning a function, but inside that function the variable @uppercase is accessed. 在构造函数中,您将返回一个函数,但是在该函数内部将访问变量@uppercase In this case, you want the this keyword (ie the @ ) to reference the object instance that is being constructed. 在这种情况下,您希望this关键字(即@ )引用正在构造的对象实例。 However, this always references the object on which the function is called, which is this case is undefined . 但是, this始终引用在其上调用函数的对象,这种情况下是undefined

To fix it, simply use the fat arrow, and CoffeeScript will set the this keyword as expected: 要解决此问题,只需使用粗箭头,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(" ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM