[英]Jasmine: how to test async function?
在我的 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 毫秒内完成(由 jasmine.DEFAULT_TIMEOUT_INTERVAL 设置)
我已将jasmine.DEFAULT_TIMEOUT_INTERVAL
增加到 20000 毫秒,但仍然无效。 如何测试此类异步功能?
我找到了双门轿跑车的例子,但它们在我的情况下不起作用: 如何用茉莉花测试具有 setTimeout 的函数?
更新
这是我的最新版本,不会引发错误,但问题是它不包括 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
});
问题是,通过使用 jasmine 的自定义时钟,您需要手动调用.tick()
来向前移动时间。 由于您立即等待wait
调用,因此不会达到wait
内的setTimeout
。 因此,当您在等待承诺后调用.tick()
,承诺永远不会解决。
您可以通过不立即等待从wait
返回的承诺而是将其分配给一个变量然后将时间向前移动来解决此问题。 然后,等待承诺并检查wait
是否已被调用:
describe('Helper methods', () => {
it('should wait a specified amount of time', async () => {
const TIMEOUT = 10000;
jasmine.clock().install(); // First install the clock
const waitPromise = wait(TIMEOUT);
jasmine.clock().tick(10000); // waits till 10000 milliseconds
await waitPromise; // now await the promise
expect(wait).toHaveBeenCalled();
jasmine.clock().uninstall(); // uninstall clock when done
});
});
请注意,在上面的代码中,没有在wait
上设置间谍,因此.toHaveBeenCalled
可能会失败。 如果您需要帮助设置函数的间谍,请查看此链接: https : //stackoverflow.com/a/43532075/3761628
回答更新的问题:您错误地设置了间谍。 您需要将其更改为:
import { setProcessEnv } from 'spec/helpers';
import * as WaitFunction from from '../../util/helpers';
...
it('should wait a specified amount of time', async () => {
const TIMEOUT = 10000;
const waitSpy = spyOn(WaitFunction, 'wait').and.callThrough();
await WaitFunction.wait(TIMEOUT);
expect(waitSpy).toHaveBeenCalled();
expect(waitSpy).toHaveBeenCalledWith(TIMEOUT);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.