javascript - Jest test durumu başarısız olduktan sonra temizleme
Bir test durumu başarısız olduğunda temizlemek için iyi ve temiz bir yol nedir? Birçok test durumu için önce temiz bir veritabanı ortamı oluşturuyorum, bu da bir test durumu tamamlandıktan sonra temizlenmesi gerekiyor.
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
await cleanup();
});
Sorun şu ki: Eğer expects'lerden biri başarısız olursa, cleanup() çağrılmaz ve dolayısıyla veritabanı ortamı temizlenmez ve bağlantı kapatılmadığı için jest Jest did not exit one second after the test run has completed. diye şikayet eder.
Mevcut geçici çözümüm böyle görünüyor, ancak temizlik kancalarını bir diziye itip bunun ardından afterAll olayında işlenmesi iyi ve temiz hissettirmiyor.
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();
});
Cevap #1
Böyle durumlar için try/finally bloğu kullanın.
Örneğin:
it("some test case", async done => {
try {
expect(false).toEqual(true);
console.log("abc");
done();
}finally{
console.log("finally");
// cleanup code below...
}
});
Yukarıdaki kod sadece finally bloğunu çalıştırır (bu nedenle konsolda "abc" yerine "finally" yazdırılır. Dikkat edin, catch bloğu bir zaman aşımı verir, bu yüzden sadece finally kullanın.
Bu cevap yararlı olmalı.
Cevap #2
Peki afterEach() kullanırsan ne olur? Her testten sonra çalıştırılacaktır
test('some test', async () => {
const { sheetService, cleanup } = await makeUniqueTestSheetService();
// do tests with expect()
});
afterEach(async()=>{
await cleanup();
});
