TypeError:尝试分配给readonly属性

时间:2013-11-18 18:45:35

标签: javascript angularjs unit-testing karma-runner

我在为指令编写测试时遇到此错误(使用generator-angular-module):

的src / capitalize.js:

'use strict';

angular.module('jviotti.string', []).filter('capitalize', function() {

  return function(input) {
    return input.replace(/\w\S*/g, function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
  };

});

测试/规格/ capitalize.js:

'use strict';

describe('Filter: capitalize', function () {

  // load the controller's module
  beforeEach(module('jviotti.string'));

  var capitalize;
  beforeEach(inject(function($filter) {
    capitalize = $filter('capitalize');
  }));

  it('should capitalize a string', function () {
    expect(capitalize('hello')).toBe('Hello');
  });

});

然而,当使用PhantomJS运行Karma时,我得到:

PhantomJS 1.9.2 (Mac OS X) Filter: capitalize should capitalize a string FAILED
    TypeError: Attempted to assign to readonly property.
        at workFn (/Users/jviotti/Projects/angular-string/bower_components/angular-mocks/angular-mocks.js:2107)
    TypeError: 'undefined' is not a function (evaluating 'capitalize('hello')')
        at /Users/jviotti/Projects/angular-string/test/spec/capitalize.js:14
PhantomJS 1.9.2 (Mac OS X): Executed 2 of 2 (1 FAILED) (0.1 secs / 0.017 secs)

我错过了什么?

5 个答案:

答案 0 :(得分:31)

改变karma.conf.js

  logLevel: config.LOG_INFO,

  logLevel: config.LOG_DEBUG,

和PhantomJS到Firefox,然后你会得到更详细的错误消息

答案 1 :(得分:8)

另一种选择(在Angular 1.2.2中)是在angular-mocks.js文件中注释掉第2107行:

if(e.stack && errorForStack) e.stack +=  '\n' + errorForStack.stack;

显然在PhantomJS中,错误堆栈是只读的。

编辑:

在Angular 1.2.10+(github.com/angular/angular.js/pull/5047)中不应再出现此错误(谢谢sherlocken!)

答案 2 :(得分:2)

我也在v1.2.5中看到了这个问题。它似乎是angular-mocks.js中的回归:https://github.com/angular/angular.js/pull/5047

您可以从此差异手动修补angular-mocks.js:https://github.com/wizardwerdna/angular.js/commit/17515763b891ea617339610fe92079cefe0efbbe

答案 3 :(得分:2)

升级到至少1.2.10可能有所帮助,它将PhantomJS和某些其他浏览器的问题合并在一起。请参阅https://github.com/angular/angular.js/pull/5047https://github.com/angular/angular.js/tree/v1.2.10

答案 4 :(得分:1)

您是否在规范顶部添加了参考js文件,如下所示

/// <reference path="../../../bower_components/angular/angular.js" />
/// <reference path="../../../bower_components/angular-route/angular-route.js" />
/// <reference path="../../../bower_components/angular-ui-router/release/angular-ui-router.js" />
/// <reference path="../../../bower_components/jasmine/lib/jasmine-core/jasmine.js" /> 
/// <reference path="../../../bower_components/jasmine/lib/jasmine-core/jasmine-html.js" />
/// <reference path="../../../bower_components/jasmine/lib/jasmine-core/boot.js" />
/// <reference path="../../../bower_components/angular-mocks/angular-mocks.js" />

注意:angular-mocks.js必须在angular.js之后和测试文件之前