测试不在服务内的异步功能 [英] Test an asynchronous function not within a service
本文介绍了测试不在服务内的异步功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一条指令从范围中获取一个函数,并且该函数是异步的,我该如何测试呢?例如
If I have a directive that takes a function from the scope, and that function is asynchronous how could I test that? For example
angular.module('myApp').factory('AsyncService',() => {
return {
async: // function that returns a promise
}
})
angular.module('myApp').directive('asyncDirective', () => ({
scope: { async: = },
link: scope => {
scope.async.then(//do something)
}
}));
angular.module('myApp').controller('ctrl', ($scope, AsyncService) => {
$scope.asyncService = AysncService;
});
<async-directive async="asyncService.async" />
上面的代码是如何使用指令的示例,但是我只想单独测试指令.由于该指令需要的是函数而不是可以用来调用函数的对象,因此我将如何测试它?如果我使用间谍,我会怎么监视?
The above code is an example of how the directive might be used, but I only want to test the directive alone. Since the directive expects a function and not an object that it can use to call a function, how would I test it? If I used a spy, what would I spy on?
推荐答案
服务应存根:
beforeEach(() => {
module('myApp', { AsyncService: { async: jasmine.createSpy() } });
})
然后可以模拟该方法以在指令编译之前返回promise:
Then the method can be mocked to return a promise before directive compilation:
AsyncService.async.and.returnValue($q.resolve(...));
这篇关于测试不在服务内的异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文