gpt4 book ai didi

javascript - Angular 2 测试 : What's the correct way for async testing?

转载 作者:行者123 更新时间:2023-11-30 11:49:54 25 4
gpt4 key购买 nike

我在一个带有 karma 和 jasmine 的 angular 2 项目中进行了以下测试:

let a: any;

beforeEach(() => {
a = {};

setTimeout(() => {
a.test();
}, 1000);
});

it('should work with async and promise', async(() => {

return new Promise((resolve) => {
a.test = () => {
console.log('erster test');
assertThat(true, is(false));
resolve();
};
});
}));

it('should work with async and done', async((done) => {

a.test = () => {
console.log('zweiter test');
assertThat(true, is(false));
done();
};
}));

it('should work with done', (done) => {

a.test = () => {
console.log('dritter test');
assertThat(true, is(false));
done();
};
});

唯一有效(意味着它失败)的情况是最后一个只有“完成”回调的情况。对于第二个,我不确定,但第一个不应该是在 angular 2 中测试异步的正确方法吗?我想用“异步”你在你的函数周围放置一个区域并且它正在等待返回的 promise ?我试图理解异步实现,但我不明白:https://github.com/angular/angular/blob/master/modules/%40angular/core/testing/async.ts

最佳答案

区域已创建inside the async method .所以您的 setTimeout(在 beforeEach 中)不在该区域内。如果您将 setTimeout 移动到 inside async 回调,那么它就在区域中,并且测试应该按预期工作(意味着等待要完成的异步任务)。

it('should work with async and promise', async(() => {
setTimeout(() => {
a.test();
}, 1000);
return new Promise((resolve) => {
a.test = () => {
console.log('erster test');
expect(true).toBe(false);
resolve();
};
});
}));

it('should work with async and done', async((done: Function) => {
setTimeout(() => {
a.test();
}, 1000);
a.test = () => {
console.log('zweiter test');
expect(true).toBe(false);
done();
};
}));

关于javascript - Angular 2 测试 : What's the correct way for async testing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39772560/

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