【发布时间】:2013-04-28 06:03:12
【问题描述】:
我为此被困了几个小时,这是因为我是 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 为 [] 则消息应为“请来很快回来”。
'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");
}));
});
测试没有完成,因为我不知道如何从promise 存根then
非常感谢任何帮助。谢谢。
【问题讨论】:
-
很抱歉,我目前无法提供更长的答案,但我会将
SomeService.getObjs存为一个假函数,它会返回一个自定义承诺(使用$q),即你控制。 -
非常感谢您的回复,但如果您稍后能给我示例代码。那太好了。
-
我也尝试过这样做,但我不知道如何存根回调函数参数。
标签: javascript unit-testing angularjs jasmine