如果我有以下代码:
public returnData(): Promise<any> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
data: true,
});
}, 2000);
});
}现在,我的单元测试成功地完成了:
it('should return data', async function () {
const responseMock = {
data: true,
};
await expectAsync(component.returnData()).toBeResolvedTo(responseMock);
});但有一个明显的问题:测试需要超过2000毫秒,这是不可接受的。我想不需要等待时间就能测试这个。我尝试过许多不同的解决方案,如下所示:
it('should return data', async function () {
jasmine.clock().install();
const responseMock = {
data: true,
};
setTimeout(() => {
expectAsync(component.returnData()).toBeResolvedTo(responseMock);
jasmine.clock().tick(2000);
}, 2000);
jasmine.clock().uninstall();
});上面的测试以很好的时间通过了,但是当我更改其他任何东西的responseMock值时,它仍然通过,所以它并不是真正有效的.
在不需要等待setTimeout时间的情况下,测试这个特定案例的关键是什么?
发布于 2022-01-20 13:50:44
为什么要在setTimeout中运行期望呢?也许我们不需要那个。
试试这个:
it('should return data', async function () {
jasmine.clock().install();
const responseMock = {
data: true,
};
// call the method that returns a promise and have a handle on its promise
const promise = component.returnData();
// make 2 seconds pass in a fake way
jasmine.clock().tick(2000);
// await the promise
const result = await promise;
// assert the result
expect(result).toEqual(responseMock);
jasmine.clock().uninstall();
});我看到你用的是component.,很可能你用的是角度。如果你用的是角度,我用fakeAsync/tick来表示时间和承诺。
看看fakeAsync/tick 这里。
//
it('should return data', fakeAsync(() => {
const responseMock = {
data: true,
};
// call the method that returns a promise and have a handle on its promise
const promise = component.returnData();
// make 2000 pass in a fake way
tick(2000);
promise.then(result => {
expect(result).toEqual(responseMock);
expect(1).toBe(2); // delete this - make sure the test fails to know we made it here
});
}));https://stackoverflow.com/questions/70784496
复制相似问题