Testing an AngularJS factory with Karma (Jasmine)(使用 Karma (Jasmine) 测试 AngularJS 工厂)
本文介绍了使用 Karma (Jasmine) 测试 AngularJS 工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力使用 Karma + Jasmine 测试 AngularJS 工厂.
I'm struggling with testing an AngularJS factory using Karma + Jasmine.
我无法将我的工厂注入到 OfficerValidationService
变量中.
I am unable to inject my factory to OfficerValidationService
variable.
我做错了什么?
注意:文件加载正确
工厂:
'use strict';
angular.module('darthvader').factory('OfficerValidationService', [function(){
var OfficerValidationService = {};
OfficerValidationService.something = function() {
return true;
};
return OfficerValidationService;
}]);
代码:
'use strict';
(function() {
describe('OfficerValidationService Spec', function() {
var OfficerValidationService;
beforeEach(function() {
angular.module('darthvader');
});
beforeEach(module('darthvader', function($provide) {
$provide.value('OfficerValidationService', OfficerValidationService);
}));
it('is very true', inject(function(OfficerValidationService){
alert('=====' + OfficerValidationService + '=====');
var output = OfficerValidationService.something();
expect(output).toBeTruthy();
}));
});
}());
输出:
Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket yc_qTseOCArRtZLAXSTZ with id 97647403
ALERT: '=====undefined====='
PhantomJS 1.9.7 (Mac OS X) OfficerValidationService Spec is very true FAILED
TypeError: 'undefined' is not an object (evaluating 'OfficerValidationService.something')
at /Users/chuck/Desktop/sandbox/dashboard.darthvader/test/karma/unit/services/officerValidationService.js:25
at invoke (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular/angular.js:3917)
at workFn (/Users/chuck/Desktop/sandbox/dashboard.darthvader/public/lib/angular-mocks/angular-mocks.js:2155)
undefined
PhantomJS 1.9.7 (Mac OS X): Executed 28 of 28 (1 FAILED) (0.102 secs / 0.131 secs)
推荐答案
需要调用angular.injector
:
'use strict';
(function() {
describe('OfficerValidationService Spec', function() {
var OfficerValidationService;
beforeEach(function() {
angular.module('darthvader');
});
beforeEach(inject(function() {
var $injector = angular.injector(['darthvader']);
OfficerValidationService = $injector.get('OfficerValidationService');
}));
it('is very true', function(){
var output = OfficerValidationService.something();
expect(output).toBeTruthy();
});
});
}());
这篇关于使用 Karma (Jasmine) 测试 AngularJS 工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用 Karma (Jasmine) 测试 AngularJS 工厂
基础教程推荐
猜你喜欢
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06