gpt4 book ai didi

angularjs - 使用 angularjs 测试 promise

转载 作者:行者123 更新时间:2023-11-28 20:40:44 26 4
gpt4 key购买 nike

我有这个工厂和她的测试:

angular.module('testApp')
.factory('bar', function ($q) {
// Service logic
// ...

var meaningOfLife = 42;

// Public API here
return {
someMethod: function () {
var deferred = $q.defer();

setTimeout(function() {
deferred.resolve();
}, 1000);

return deferred.promise;
}
};
});


'use strict';

describe('Service: bar', function() {

// load the service's module
beforeEach(module('testApp'));

it('should do something', function(done) {
inject(function (bar) {
var promise = bar.someMethod();
promise.then(function(){
expect(!!bar).toBe(true);
done();
});
});
});
});

测试返回这个:

在 jasmine.DEFAULT_TIMEOUT_INTERVAL 指定的超时时间内未调用异步回调

我知道在工厂中用 $timeout 替换 setTimeout 并在测试中添加 $timeout.flush(),它有效。

但是,我想了解如何使用 setTimeout 而不是 $timeout 来进行此测试。

最佳答案

那是因为 setTimeout() 没有在 AngularJS 的摘要循环中运行。您应该使用 $timeout 而不是 setTimeout。此外,在这种情况下,使用 jasmine 的 done() 回调函数并不适合,因为您可以清除所有同步存储的排队延迟函数。

DEMO

angular.module('testApp', [])
.factory('bar', function ($q, $timeout) {
// Service logic
// ...

var meaningOfLife = 42;

// Public API here
return {
someMethod: function () {
var deferred = $q.defer();

$timeout(function() {
deferred.resolve();
}, 1000);

return deferred.promise;
}
};
});


'use strict';

describe('Service: bar', function() {

// load the service's module
beforeEach(module('testApp'));

it('should do something', function() {
inject(function (bar, $timeout) {
var promise = bar.someMethod();
promise.then(function(){
expect(!!bar).toBe(true);
});
// flush out queued deferred functions!
$timeout.flush();
});
});
});

关于angularjs - 使用 angularjs 测试 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34017720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com