我试图测试一个角色服务,该服务在mocha chai中返回一个承诺,但是调用'然后'在单元测试中超时。我的服务依赖于具有异步$资源请求的第二个服务。 myService.getData()应该从内部获取来自所述异步服务的数据并将promise传递给控制器,该控制器调用'然后'对响应起作用。这在控制器中运行良好,并且在单元测试中绝对失败。
服务代码:
// use: myService.getData.then(...) works beautifully in angular controllers
getData = function(dataId) {
var dataPromise;
// get students from the api, if necessary, or from the service if already retrieved
// dataList is a private property of the service
if(!dataList) {
dataPromise = asyncServiceUsedByMyService.asyncMethod({...}).$promise
.then(
function(response){
dataList = response;
doSomeDataManipulation();
return dataList;
},
function(err) {
return err;
}
);
}
// use the existing studentList if available
else {
dataPromise = $q.when(function(){
return dataList
});
}
return dataPromise;
};
测试代码
describe('Service Test', function() {
var expect = chai.expect,
myService,
asyncServiceUsedByMyService;
beforeEach(function() {
var data,
asyncServiceMock;
data =[...];
// mock the async dependency
asyncServiceMock = {
asynchMethod: function () {
var deferred = q.defer();
deferred.resolve(data);
return {$promise: deferred.promise};
}
};
module('myApp');
module(function($provide){
$provide.value('asyncServiceUsedByMyService', asyncServiceMock);
});
inject(function(myService, $q, asyncServiceUsedByMyService) {
myService = myService;
q = $q;
courseEnrollmentService = courseEnrollmentServiceMock;
});
});
// passes
it('should be available', function() {
expect(!!myService).to.equal(true);
});
// 'then' function is never called, unit test times out
it('should get all items from async dependency', function(done) {
myService.getData().then(function(response) {
expect(response).to.have.property('length').that.equals(5);
done();
});
});
});
如何获得'然后' myService的功能在单元测试中运行,因此它将获得模拟数据(这应该是即时的,因为我们没有进行实际的api调用?)。
注意:我也尝试过“承诺”#39;语法,但以下似乎超时
it('should get all items from async dependency', function(done) {
expect(myService.getData()).to.eventually.have.property('length').that.equals(5).and.notify(done);
});