我正在尝试通过Karma用Jasmine测试我的AngularJS应用。我收到此错误(至少,这是最新的错误):
Uncaught TypeError: Cannot read property '$modules' of null
at /Users/benturner/Dropbox/Code/galapagus/app/static/js/angular-mocks.js:1866
从我的karma.conf.js中:
files: [
'static/js/jquery.min.js',
'static/js/angular.min.js',
'static/js/angular-mocks.js',
'static/js/angular-resource.min.js',
'static/js/angular-scenario.js',
'static/js/angular-loader.min.js',
'static/js/momentous/ctrl_main.js', // contains all my app's code
'test/momentous.js'
],
这是我的测试:
(function () {
"use strict";
var controller = null;
var scope = null;
describe("Services", inject(function($rootScope, Moments) {
var mockedFactory, moments, flag, spy;
moments = [{name: 'test'}];
beforeEach(module('momentous', function($provide) {
scope = $rootScope.$new();
$provide.value('$rootScope', scope);
mockedFactory = {
getList: function() {
return moments;
}
};
spy = jasmine.createSpy(mockedFactory.getList);
$provide.value('Moments', mockedFactory);
}));
it('should return moments from the factory service', function() {
runs(function() {
console.log(scope.getList);
flag = false;
setTimeout(function() {
scope.getList();
flag = true;
}, 500);
});
waitsFor(function() {
return flag;
}, "The call is done", 750);
runs(function() {
expect(scope.moments).toEqual([{name: 'test'}]);
expect(spy).toHaveBeenCalled();
});
});
}));
}());
所以我想做的是模拟我的工厂服务,并检查它是否返回对象数组并将它们设置为$ scope中的变量。
那里也有一个异步调用,所以我不得不使用runs()和waitsFor()。
我仍然不明白我如何注入(inject)$ scope以便可以对其进行测试,并且使用angular-mocks.js现在给我一个错误,我觉得我距离解决这个问题越来越近了,而不是更进一步。
我从各种文档,指南和stackoverflow答案中总结了这一点。有指导吗?谢谢。
最佳答案
我也一直卡住这个确切的错误。我的代码与尝试测试提供程序的地方类似,因此我调用module并将其传递给配置提供程序的函数。
解决了:
我发现问题是由于调用“注入(inject)”将委托(delegate)返回到“描述”方法所致。您只能使用注入(inject)将委托(delegate)返回给“它”。
例如:
describe('something', inject(function(something) {})); // will throw the $module is null error
但这将起作用:
it('something', inject(function(something) {})); // works :)
关于javascript - 使用Jasmine在Karma中进行AngularJS工厂测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18977425/