gpt4 book ai didi

javascript - 使用 Jasmine 测试 Angular Promise

转载 作者:可可西里 更新时间:2023-11-01 01:25:08 25 4
gpt4 key购买 nike

以下测试一直失败,我不明白为什么?我正在尝试弄清楚如何使用 Jasmine 测试延迟/ promise 。

错误

Expected undefined to be 'Resolved Data'.

测试

    describe('Queued Repository', function () {
var ctrl,
rootScope,
scope,
service;

beforeEach(function () {
module('testApp');

inject(function ($rootScope, $controller, TestSrvc) {
rootScope = $rootScope;
scope = $rootScope.$new();
service = TestSrvc;
});
});

afterEach(inject(function ($rootScope) {
$rootScope.$apply();
}));

it('test something', function () {
expect(service.calculate(1, 5)).toBe(6);
});

it('resolves promises', function () {
var result;

service.getPromise().then(function (data) {
result = data;
});

rootScope.$apply();
expect(result).toBe('Resolved Data');
});
});

服务

    var app = angular.module('testApp', []);

app.service('TestSrvc', ['$q', '$timeout', '$http', function ($q, $timeout, $http) {
return {
getPromise: function () {
var d = $q.defer();

$timeout(function () {
d.resolve('Defered Result');
}, 5000);

return d.promise;
},
getSomething: function () {
return "Test";
},
calculate: function (x, y) {
return x + y;
}
}
}]);

最佳答案

尝试在 expect(result).toBe('Resolved Data'); 之前调用 $timeout.flush()

关于javascript - 使用 Jasmine 测试 Angular Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19718282/

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