我想编写一个单元测试,只显示创建两个 promise 的行为,用 $q.all 将它们包装成一个,然后测试这两个 promise 是否同时得到解决。
describe("Application controller", function() {
var scope;
var controller;
beforeEach(module('my.namespace'));
//this suite can be removed.
describe("Application ", function() {
beforeEach(
inject(function ($rootScope, $controller,$q) {
scope = $rootScope.$new();
controller = $controller('Application', {
'$scope': scope
});
}));
it("should package two promises into one", function (done) {
inject(function ($rootScope) {
setTimeout(function () {
$rootScope.$apply(function () {
var promiseOne = $q.defer(),
//promiseOneData;
promiseTwo = $q.defer();
//promiseTwoData
promiseOne.then(function(data){
promiseOne.resolve('promiseOne');
expect(1).toBe(1);
});
promiseTwo.then(function(data){
promiseTwoData.resolve('promiseTwo');
})
var allPromises = $q.all([promiseOne,promiseTwo]);
allPromises.then(function(data){
//data should contain an array of two empty elements for each promise
expect(data.length).toBe(2);
});
done();
});
}, 1000);
})
});
有了这个我得到了错误:Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
我不想在这里对任何东西实际使用 get 请求,我只需要解决两个 promise ,然后将其转移到一个包含两个 promise 的 promise 中。我如何使用 Angular 和 jasmine 做到这一点?
最佳答案
你想要的可能是一个 spy ,看看它是否被调用过。
describe('test $q', function() {
var
$scope;
$controller;
$httpBackend;
beforeEach(function() {
module('myModule');
inject(function(_$rootScope_, _$controller_) {
$scope = _$rootScope_.$new();
$controller = _$controller_;
$controller ('MyCtrl', {
$scope: $scope
});
});
it('should test that $q.all calls callback when dependent promises are resolved', function() {
var deferOne = $q.defer(),
deferTwo = $q.defer();
combinedSpy = jasmine.createSpy('combined');
$q.all([deferOne.promise, deferTwo.promise]).then(combinedSpy);
expect(combinedSpy).toNotHaveBeenCalled();
deferOne.resolve();
deferTwo.resolve();
$scope.apply();
expect(combinedSpy).toHaveBeenCalled();
});
这个测试标题很困惑,你不是在模拟一个 promise 。你正在测试一个 promise 。而且您不必这样做,Angular 本身已经对 $q 进行了测试,所以您为此编写测试没有意义吗?
wrapping them up into one with $q.all
这创造了第三个 promise 。当 promise A 和 B 都被 resolved 时,第三个 promise 被 resolved。
test that the promises are both resolved at the same time
JavaScript 是单线程的,它们不能同时解析。第三个 promise ,即由 $q.all() 创建的 promise ,将在第一个和第二个都已解决时解决。解决 A 和 B 之间的时间可能会过去。
说A解决了,一小时后B解决了。然后 C ($q.all) 将在下一个摘要循环中解析(通过 $scope.apply())。
关于javascript - 用于 promise 的 Angular Jasmine 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24329874/