AngularJS工厂在Karma与Jasmine进行测试
AngularJS factory testing in Karma with Jasmine
我正在尝试通过Karma用Jasmine测试我的AngularJS应用程序。 我收到此错误(至少,这是其中最新的):
Uncaught TypeError: Cannot read property '$modules' of null
at /Users/benturner/Dropbox/Code/galapagus/app/static/js/angular-mocks.js:1866
来自我的业力.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()。
我仍然不明白我是如何注入我的$scope以便我可以针对它进行测试的,并且使用角度模拟.js现在给我一个错误,我觉得我离解决这个问题越来越远,而不是更近了。
我从各种文档、指南和 stackoverflow 答案中拼凑了这个。 有什么指导吗? 谢谢。
我也遇到了这个确切的错误。 我的代码类似于我尝试测试提供程序的地方,因此我调用模块并向其传递配置提供程序的函数。
解决:
我发现问题是由于调用"注入"以将委托返回"描述"方法。 您只能使用 inject 将委托返回给"it"。
例如:
describe('something', inject(function(something) {})); // will throw the $module is null error
但这将起作用:
it('something', inject(function(something) {})); // works :)
相关文章:
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- Jasmine单元测试在监视服务方法时失败
- 如何使用Jasmine测试Knockout.js点击绑定
- 如何在jasmine测试中为有角度的项目注入依赖项
- 测试iFrame的位置.href是在jasmine单元测试中设置的
- 在Karma Jasmine单元测试用例中检查日期格式
- Jasmine:测试setTimeout函数会抛出一个错误
- 如何通过 phantomjs 可靠地执行利用 requirejs 的 Jasmine 测试
- 当使用Jasmine在JS中测试AJAX调用时,.andReturn(..)和.respondWith(
- 使用jasmine测试JavaScript回调函数
- 如何在Jasmine/Rect中测试带有范围输入的“onChange”事件
- Jasmine测试工厂函数调用本地函数和另一个函数-获取错误:应该是间谍,但得到了function
- 使用$httpBackend测试Jasmine/Karma的AngularJS不起作用
- 如何测试Jasmine设置代码
- 测试Jasmine测试是否失败
- expect - response在AngularJS单元测试(Jasmine)中不起作用
- 重构单元测试(Jasmine)
- 测试Jasmine中的Rails Route
- 使用特定的keyCode测试Jasmine中的keydown事件
- 单元测试——jasmine, javascript