[英]How to add unit testing in strapi version 4 using jest?
我正在嘗試在全新的 Strapi 應用程序上添加單元測試。 官方文檔仍在進行中。 那么,在文檔准備好之前,有沒有辦法將 jest 單元測試添加到 Strapi 應用程序中? 我按照 v3 文檔中的方法沒有運氣。
我陷入了同樣的問題,我目前正在嘗試使單元測試文檔中的所有測試都通過,但到目前為止我還停留在用戶測試中。 這是我的設置:
const fs = require("fs");
const { setupStrapi } = require("./helpers/strapi");
jest.setTimeout(15000);
beforeAll(async () => {
await setupStrapi();
});
afterAll(async () => {
const dbSettings = strapi.config.get("database.connections.default.settings");
//close server to release the db-file
await strapi.server.httpServer.close();
//delete test database after all tests
if (dbSettings && dbSettings.filename) {
const tmpDbFile = `${__dirname}/../${dbSettings.filename}`;
if (fs.existsSync(tmpDbFile)) {
fs.unlinkSync(tmpDbFile);
}
}
// await strapi.db.connection.destroy(); // Note on this below
});
it("strapi is defined", () => {
expect(strapi).toBeDefined();
});
require('./hello');
await strapi.db.connection.destroy();
應該破壞連接上下文並防止此問題,但我無法使其工作。
讓實例;
async function setupStrapi() {
if (!instance) {
await Strapi().load();
instance = strapi;
await instance.server.mount();
}
}
module.exports = { setupStrapi };
const request = require('supertest');
it('should return hello world', async () => {
await request(strapi.server.httpServer)
.get('/api/hello')
.expect(200) // Expect response http code 200
});
請注意,您需要在項目中擁有 /hello 端點,如Strapi 文檔中指定的那樣,測試才能通過。
我希望這可以幫助任何在同樣問題上苦苦掙扎的人。 隨着我的進步,我會更新答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.