Vet*_*ack 4 javascript testing typescript jestjs
测试用例失败后清理的好方法是什么?对于很多测试用例,我首先创建了一个干净的数据库环境,需要在一个测试用例完成后进行清理。
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
await cleanup();
});
Run Code Online (Sandbox Code Playgroud)
问题是:如果其中一个expects失败,cleanup()则不会被调用,因此数据库环境没有被清理,并且 jest 会Jest did not exit one second after the test run has completed.因为连接没有关闭而抱怨。
我当前的解决方法看起来像这样,但是将清理挂钩推送到afterAll事件中处理的数组感觉并不好和干净。
const cleanUpHooks: (() => Promise<void>)[] = [];
afterAll(async () => {
await Promise.all(cleanUpHooks.map(hook => hook()));
});
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
await cleanup();
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下使用 try/finally 块。
例如:
it("some test case", async done => {
try {
expect(false).toEqual(true);
console.log("abc");
done();
}finally{
console.log("finally");
// cleanup code below...
}
});
Run Code Online (Sandbox Code Playgroud)
上面的代码只会执行 finally 块(因此“finally”被打印在控制台而不是“abc”中。请注意,catch 块会给出超时,因此只需使用finally.
这个答案一定有用。
如果使用 afterEach() 会怎样?它将在每次测试后执行
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
});
afterEach(async()=>{
await cleanup();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1664 次 |
| 最近记录: |