你的完整测试是什么样的?我也遇到了这个错误。我的测试看起来像这样:
'use strict';
describe("CalendarController", function() {
var scope, $location, $controller, createController;
var baseTime = new Date(2014, 9, 14);
spyOn(Date.prototype, 'getMonth').andReturn(baseTime.getMonth());
spyOn(Date.prototype, 'getDate').andReturn(baseTime.getDate());
spyOn(Date.prototype, 'getFullYear').andReturn(baseTime.getFullYear());
var expectedMonth = fixture.load("months.json")[0];
beforeEach(module('calendar'));
beforeEach(inject(function ($injector) {
scope = $injector.get('$rootScope').$new();
$controller = $injector.get('$controller');
createController = function() {
return $controller('CalendarController', {
'$scope': scope
});
};
}));
it('should load the current month with days', function(){
var controller = createController();
expect(scope.month).toBe(expectedMonth);
});
});
请注意,SpyOn 函数位于描述块中。查看 jasmine 代码时,我们发现 SpyOn 应该位于 abeforeEach
或it
块中:
jasmine.Env.prototype.it = function(description, func) {
var spec = new jasmine.Spec(this, this.currentSuite, description);
this.currentSuite.add(spec);
this.currentSpec = spec;
if (func) {
spec.runs(func);
}
return spec;
};
...
jasmine.Env.prototype.beforeEach = function(beforeEachFunction) {
if (this.currentSuite) {
this.currentSuite.beforeEach(beforeEachFunction);
} else {
this.currentRunner_.beforeEach(beforeEachFunction);
}
};
这些是设置的地方currentSpec
。否则这将为空。所以在我的例子中应该是:
'use strict';
describe("CalendarController", function() {
var scope, $location, $controller, createController;
var baseTime = new Date(2014, 9, 14);
var expectedMonth = fixture.load("months.json")[0];
beforeEach(module('calendar'));
beforeEach(inject(function ($injector) {
scope = $injector.get('$rootScope').$new();
$controller = $injector.get('$controller');
createController = function() {
return $controller('CalendarController', {
'$scope': scope
});
};
}));
it('should load the current month with days', function(){
spyOn(Date.prototype, 'getMonth').andReturn(baseTime.getMonth());
spyOn(Date.prototype, 'getDate').andReturn(baseTime.getDate());
spyOn(Date.prototype, 'getFullYear').andReturn(baseTime.getFullYear());
var controller = createController();
expect(scope.month).toBe(expectedMonth);
});
});
然后这将起作用,因为 spyOn 在 it 块中。希望这可以帮助。