【问题标题】:Undefined is not a function is CoffeeScript / Angular / JasmineUndefined is not a function is CoffeeScript / Angular / Jasmine
【发布时间】:2015-06-13 15:07:44
【问题描述】:

我根据Angular unit-testing documentation 中的示例编写了一个简短的单元测试。我试图创建一个没有运气的jsfiddle,所以请多多包涵。

# app definition
app = module 'myApp', []
.controller 'myCtrl', ['$scope', ($scope) ->$scope.foo = 'foo']

# test
describe 'myCtrl tests', () ->
  beforeEach module 'myApp'
  $controller = undefined

  beforeEach inject (_$controller_) ->
    $controller = _$controller_

  describe 'myCtrl', () ->
    it 'should not throw an error', () ->
      $scope = {}
      controller = $controller 'myCtrl',{$scope: $scope}
      expect ($scope.foo).toEqual 'foo'

当我运行这个测试时,我得到“TypeError: undefined is not a function” 对于 $scope.foo 并且测试失败。

【问题讨论】:

    标签: angularjs unit-testing coffeescript jasmine karma-jasmine


    【解决方案1】:

    你的

    expect ($scope.foo).toEqual 'foo'
    

    正在被转译为:

    expect($scope.foo.toEqual('foo'));
    

    所以,javascript 认为 $scope.foo 是一个函数(它不是)。请记住,CoffeeScript 中的空格表示您正在将参数传递给函数。

    您似乎想要的是以下任何一种:

    expect $scope.foo
        .toEqual 'foo'
    

    expect($scope.foo).toEqual 'foo'
    

    这些都会变成:

    expect($scope.foo).toEqual('foo');
    

    【讨论】:

      【解决方案2】:

      考虑以下两行 CoffeeScript 代码:

      expect ($scope.foo).toEqual 'foo'  # line 1
      expect($scope.foo).toEqual 'foo'   # line 2
      

      您可能希望它们生成相同的 JavaScript 代码,但它们不会:

      expect($scope.foo.toEqual('foo')) // line 1
      expect($scope.foo).toEqual('foo') // line 2
      

      从您链接的示例中,很容易看出您想要的是第二行,而不是前者。

      【讨论】:

      • 太棒了!就是这样。我知道它一定是 CoffeeScript gremlin。
      猜你喜欢
      • 1970-01-01
      • 2014-06-29
      • 2015-06-24
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2015-01-14
      相关资源
      最近更新 更多