我为此而坚持了好几个小时,因为我是Jasmine和Angularjs的新手。基本上,我有这个控制器。
angular.module('toadlane.controllers', []).
controller('MainController', function($scope, $http, SomeService) {
var promise = SomeService.getObjects();
promise.then(function(data) {
if(data.length > 0) {
$scope.objs = data;
} else {
$scope.message = "Please come back soon";
}
});
});
如何编写Jasmine测试来模拟SomeService来存根data
并模拟数据scope
的长度是否不应为0且data
1}}是[]消息应该是"请尽快回来"。
'use strict';
describe('controllers', function () {
var scope, someService;
beforeEach(module('services'));
beforeEach(module('controllers'));
beforeEach(inject(function (SomeService) {
someService = SomeService;
var callback = jasmine.createSpy();
someService.getObjs().then(callback);
}));
it('should return some objs', inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
expect($controller('MainController', {$scope: scope, SomeService : someService})).toBeTruthy();
expect(scope.objs.length).toEqual(2);
}));
it('should return no objs', inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
expect($controller('MainController', {$scope: scope, SomeService : someService})).toBeTruthy();
expect(scope.message).toEqual("Please come back soon");
}));
});
测试尚未完成,因为我不知道如何从then
promise
非常感谢任何帮助。感谢。
答案 0 :(得分:7)
可以通过使用链接方法返回对象的函数模拟promises来测试延迟。在这种情况下,模拟SomeService.getObjs
应返回方法then
的对象。
为此,请添加另一个beforeEach
语句:
beforeEach(module(function ($provide) {
$provide.value('SomeService', {
getObjs: function () {
return {
then: function (callback) {
// mockedResponseData is passed to callback
callback(mockedResponseData);
}
};
}
}));
模拟服务将立即加载现有的promise回调函数。