我不确定这个测试哪里出错了。
服务代码:
self.clearMessage = function(interval) {
if (!interval)
interval = 2000;
return $timeout(function() {
return '';
}, interval);
};
规范:
it('clears message', function() {
var result = self.clearMessage();
$timeout.flush();
expect(result).toBe('');
});
我还尝试在测试中触发摘要循环但没有成功。我以前从未遇到过这个问题,因为我通常会在超时 block 内设置一个外部变量——这对单元测试来说效果很好。
在这种情况下,当超时内只有返回时,我收到以下错误:
预期 Promise({ $$state: Object({ status: 1, value: '' }), $$timeoutId: 1 }) 为 ''。
编辑/回答
it('clears message', function() {
self.clearMessage().then(function(response) {
expect(response).toBe('');
})
$timeout.flush();
});
最佳答案
从您的服务代码中调用 AngularJS 的 $timeout
服务会返回一个 Promise。这个 Promise 将...“在达到超时时得到解决。 promise 将通过 fn 函数的返回值得到解决。”
https://docs.angularjs.org/api/ng/service/$timeout
您的规范中需要这样的内容:
var result = self.clearMessage();
result.then(function(value) {
expect(value).toBe('');
});
$timeout.flush();
关于javascript - Jasmine ,AngularJS : Unit test a function which returns a value after timeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155167/