gpt4 book ai didi

javascript - AngularJS单元测试: using async/await with Jasmine

转载 作者:行者123 更新时间:2023-12-01 03:18:07 24 4
gpt4 key购买 nike

我正在尝试在下面相应的 (Jasmine) 单元测试中使用 async/await 关键字对我的 Angular 服务进行单元测试。对 native Promise 的测试工作得很好,但我几乎陷入了让 Angular $q 对应部分工作的困境。

  • Angular :1.6.5
  • Jasmine :2.7.0
  • ( headless )MacOS 上的 Chrome:60.x
<小时/>
angular
.module('asyncAwaitTest', [])
.factory('xService', xServiceFactory);

function xServiceFactory(
$q,
$timeout
) {
return {
getXAfter1Sec() {
return new Promise(resolve => setTimeout(() => resolve(43), 1000));
},
getXAfter1SecWithAngular$Q() {
const deferred = $q.defer();

$timeout(() => deferred.resolve(43), 1000);

return deferred.promise;
}
};
}

jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000;

describe('asyncAwaitTest: x service', () => {
let $timeout;
let xService;

beforeEach(() => {
module('asyncAwaitTest');

inject(
(
_$timeout_,
_xService_
) => {
$timeout = _$timeout_;
xService = _xService_;
}
);
});

it('should work', async (done) => {
const x = await xService.getXAfter1Sec();

expect(x).toEqual(43);

done();
});

it('should work, too. but y not?!!', async (done) => {
const xPromise = xService.getXAfter1SecWithAngular$Q();

$timeout.flush();

const x = await xPromise;

expect(x).toEqual(43);

done();
});
});

此处提供的 fiddle :https://jsfiddle.net/glenn/gaoh6bvc/

我尝试过 Google,但它并没有给我带来显着的良好领先优势 😞

最佳答案

您可以为您的测试创建一个帮助器,将 Promise 从 $q 转换为原生 Promise。看看here .

it('should work, too. but y not?!!', async (done) => {
const xPromise = toNativePromise(xService.getXAfter1SecWithAngular$Q());

$timeout.flush();

const x = await xPromise;

expect(x).toEqual(43);

done();
});

function toNativePromise(promise) {
return new Promise((resolve, reject) => {
promise.then(val => {
resolve(val);
}, err => {
reject(err);
});
});
}

关于javascript - AngularJS单元测试: using async/await with Jasmine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45402943/

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