[英]Angular Unit Tests: testing a simple promise-based function
I have a very simple mock service that I have created in my unit test for injecting into another object that I am testing. 我在单元测试中创建了一个非常简单的模拟服务,用于注入到我正在测试的另一个对象中。
beforeEach(inject(function($q, $timeout) {
ItemService = {
one: function(id) {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve({
id: id
});
}, 0);
return deferred.promise;
}
};
}));
Now I'd like to write a simple unit test that makes sure that this service returns the correct promise. 现在,我想编写一个简单的单元测试,以确保该服务返回正确的Promise。
describe('mock service', function() {
it('should return a promise', function() {
// test comes here
ItemService.one('123').then(function(item) {
// ... but doesn't make it here
expect(item.id).toEqual('123');
});
});
});
However, the code inside then()
never gets executed. 但是, then()
内部的代码永远不会执行。
The $timeout service used in unit tests is a mocked $timeout service , that needs to be flushed (just like $httpBackend). 单元测试中使用的$ timeout服务是一个模拟的$ timeout服务 ,需要刷新(就像$ httpBackend一样)。 This allows testing code that waits for 10 minutes without actually waiting for 10 minutes in the test: 这使得测试代码可以等待10分钟,而无需在测试中实际等待10分钟:
ItemService.one('123').then(function(item) {
// ... but doesn't make it here
expect(item.id).toEqual('123');
});
$timeout.flush(1);
I'm not sure that this automatically resolves the promise though, because promises are resolved the the scope is $applied. 我不确定这是否会自动解决promise,因为promise已解决,范围是$ applied。 So you might additionally need 因此,您可能还需要
$rootScope.$apply();
Of course, $timeout and $rootScope need to be injected in the test. 当然,需要在测试中注入$ timeout和$ rootScope。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.