[英]Reusing Jest unit tests
我正在嘗試使用Jest測試幾個數據庫實現。 為了幫助測試這些實現,我首先提出了一組針對API的單元測試,這兩個實現都有望實現。
我目前正在努力將這兩個實現傳遞給測試套件。
下面是一個(虛擬)MongoDB實現的最簡單形式:
class MongoDB {
async query () {
console.warn(`This is a dummy function.`)
}
async connect () {
// The real connect takes some time..instead we just simulate it
await new Promise((resolve, reject) => {
setTimeout(resolve, 300)
})
}
}
這是我測試的一小部分:
let db
beforeAll(async () => {
db = new MongoDB()
await db.connect()
console.log(`mongoDB ready`)
})
async function testDB (db) {
describe('Basic', async () => {
test('Valid instance', async () => {
expect(db).toBeTruthy()
expect(db.query).toBeTruthy()
})
})
}
describe('Tests', async () => {
console.log(`Running testDB`)
testDB(db) // Have also unsuccessfully tried changing this to: return testDB(db)
})
我使用這種方法的目的是將所有測試包裝在testDB
函數中,並簡單地使用各種實現來調用它。 例如, testDB(new MongoDB())
和testDB(new MemoryDB())
等。
但是,這似乎沒有按預期工作。 上面的代碼導致錯誤說明:
● Tests › Basic › Valid instance
expect(received).toBeTruthy()
Expected value to be truthy, instead received
undefined
console.log
語句的順序似乎表明測試在 db
初始化之前運行。
console.log mongo.test.js:20
Running testDB
console.log mongo.test.js:7
mongoDB ready
如何在不訴諸復制測試和維護兩個版本的情況下重用單元測試來測試多個實現?
今天面臨同樣的需求。 這是根據打字稿改編的方式,但你明白了:
// common/service.test.js
export const commonServiceTests = (name, impl) => {
describe(`Common tests for ${implName}`, () => {
// pile your tests here
test('test1', () => { ... });
test('test2', () => { ... });
test('test3', () => { ... });
});
}
// just to avoid warning, that no tests in test file
describe('Common tests for CommonService implementations', () => {
test('should be used per implementation', () => {});
});
並為您的每個實施:
// inmemory/service.test.js
import { commonServiceTests } from '../common/service.test';
import ...; // your implementation here
const myInMemoryService = ...; // initialize it
commonServiceTests('InMemory', myInMemoryService);
然后,在每個實現測試中將執行common/service.test.js
定義的所有測試。
如果您的初始化是async
(最有可能),那么您的共享測試也應該是async
。 然后:
// common/service.test.js
export const commonServiceTests = (name, impl: Promise) => {
describe(`Common tests for ${implName}`, () => {
// pile your async tests here
test('test1', async () => {
const svc = await impl;
return await svc.doSomthingPromisy();
});
test('test2', () => { ... });
test('test3', () => { ... });
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.