【发布时间】:2021-01-18 05:32:17
【问题描述】:
在我的 NodeJS 应用程序中,我使用一种方法获得了以下 heplers.ts 文件,wait:
export const wait = async (ms: number) => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
我目前正在为此文件编写单元测试,这就是我现在所拥有的:
import { setProcessEnv } from 'spec/helpers';
import { wait } from '../../util/helpers';
describe('Helper methods', () => {
beforeEach(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
setProcessEnv();
});
it('should wait a specified amount of time', async () => {
const TIMEOUT = 10000;
jasmine.clock().install(); // First install the clock
await wait(TIMEOUT);
jasmine.clock().tick(10000); // waits till 10000 milliseconds
expect(wait).toHaveBeenCalled();
jasmine.clock().uninstall(); // uninstall clock when done
});
});
但我不断收到
错误:超时 - 异步函数未在 20000 毫秒内完成(设置 by jasmine.DEFAULT_TIMEOUT_INTERVAL)
我已将jasmine.DEFAULT_TIMEOUT_INTERVAL 增加到 20000 毫秒,但它仍然不起作用。
如何测试这样的异步函数?
我找到了一些 coupe 示例,但它们在我的情况下不起作用:How to test a function which has a setTimeout with jasmine?
更新
这是我的最新版本,不会抛出错误,但问题是它不包括 return 语句行 (return new Promise(...):
it('should wait a specified amount of time', async () => {
const TIMEOUT = 10000;
// jasmine.clock().install(); // First install the clock
const wait = jasmine.createSpy();
await wait(TIMEOUT);
// jasmine.clock().tick(1000); // waits till 10000 milliseconds
expect(wait).toHaveBeenCalled();
expect(wait).toHaveBeenCalledWith(TIMEOUT);
// jasmine.clock().uninstall(); // uninstall clock when done
});
【问题讨论】:
-
您的测试似乎需要超过 20 秒才能执行,它需要 10 秒来执行
await wait(TIMEOUT);,另外 10 秒来执行jasmine.clock().tick(10000);。当你设置jasmine.DEFAULT_TIMEOUT_INTERVAL = 22000时会发生什么?
标签: javascript node.js unit-testing jasmine