Lia*_*nat 20 unit-testing angularjs karma-runner karma-jasmine
我有以下情况:
controller.js
controller('PublishersCtrl',['$scope','APIService','$timeout', function($scope,APIService,$timeout) {
APIService.get_publisher_list().then(function(data){
});
}));
Run Code Online (Sandbox Code Playgroud)
controllerSpec.js
'use strict';
describe('controllers', function(){
var scope, ctrl, timeout;
beforeEach(module('controllers'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new(); // this is what you missed out
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
});
}));
it('should have scope variable equals number', function() {
expect(scope.number).toBe(3);
});
});
Run Code Online (Sandbox Code Playgroud)
错误:
TypeError: Object #<Object> has no method 'get_publisher_list'
Run Code Online (Sandbox Code Playgroud)
我也试过这样的东西,它没有用:
describe('controllers', function(){
var scope, ctrl, timeout,APIService;
beforeEach(module('controllers'));
beforeEach(module(function($provide) {
var service = {
get_publisher_list: function () {
return true;
}
};
$provide.value('APIService', service);
}));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
timeout = {};
controller = $controller('PublishersCtrl', {
$scope: scope,
APIService: APIService,
$timeout: timeout
}
);
}));
it('should have scope variable equals number', function() {
spyOn(service, 'APIService');
scope.get_publisher_list();
expect(scope.number).toBe(3);
});
});
Run Code Online (Sandbox Code Playgroud)
我怎么解决这个问题?有什么建议?
Jes*_*uez 37
有两种方式(或更确切地说).
想象一下这种服务(如果它是工厂的话无关紧要):
app.service('foo', function() {
this.fn = function() {
return "Foo";
};
});
Run Code Online (Sandbox Code Playgroud)
有了这个控制器:
app.controller('MainCtrl', function($scope, foo) {
$scope.bar = foo.fn();
});
Run Code Online (Sandbox Code Playgroud)
一种方法是使用您将使用的方法创建一个对象并监视它们:
foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn("Foo");
Run Code Online (Sandbox Code Playgroud)
然后将其foo作为dep传递给控制器.无需注入服务.那可行.
另一种方法是模拟服务并注入模拟的服务:
beforeEach(module('app', function($provide) {
var foo = {
fn: function() {}
};
spyOn(foo, 'fn').andReturn('Foo');
$provide.value('foo', foo);
}));
Run Code Online (Sandbox Code Playgroud)
当你注射然后foo注射这个.
在此处查看:http://plnkr.co/edit/WvUIrtqMDvy1nMtCYAfo?p=preview
对于那些努力使答案有效的人,
从Jasmine 2.0 andReturn()开始and.returnValue()
例如,在上面的plunker的第一次测试中:
describe('controller: MainCtrl', function() {
var ctrl, foo, $scope;
beforeEach(module('app'));
beforeEach(inject(function($rootScope, $controller) {
foo = {
fn: function() {}
};
spyOn(foo, 'fn').and.returnValue("Foo"); // <----------- HERE
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {$scope: $scope , foo: foo });
}));
it('Should call foo fn', function() {
expect($scope.bar).toBe('Foo');
});
});
Run Code Online (Sandbox Code Playgroud)
(来源:Rvandersteen)
| 归档时间: |
|
| 查看次数: |
26687 次 |
| 最近记录: |