toy*_*toy 3 javascript unit-testing jasmine angularjs
我被困了好几个小时,这是因为我是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";
}
});
});
Run Code Online (Sandbox Code Playgroud)
如何写一个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");
}));
});
Run Code Online (Sandbox Code Playgroud)
这些测试没有完成,因为我不知道如何存根then从promise
非常感谢任何帮助.谢谢.
可以通过使用链接方法返回对象的函数模拟promises来测试延迟.在这种情况下,mocked SomeService.getObjs应该返回一个带方法的对象then.
为此,添加另一个beforeEach语句:
beforeEach(module(function ($provide) {
$provide.value('SomeService', {
getObjs: function () {
return {
then: function (callback) {
// mockedResponseData is passed to callback
callback(mockedResponseData);
}
};
}
}));
Run Code Online (Sandbox Code Playgroud)
模拟服务将立即加载现有的promise回调函数.
| 归档时间: |
|
| 查看次数: |
3852 次 |
| 最近记录: |