簡體   English   中英

如何使用 jest 在 Strapi 版本 4 中添加單元測試?

[英]How to add unit testing in strapi version 4 using jest?

我正在嘗試在全新的 Strapi 應用程序上添加單元測試。 官方文檔仍在進行中。 那么,在文檔准備好之前,有沒有辦法將 jest 單元測試添加到 Strapi 應用程序中? 我按照 v3 文檔中的方法沒有運氣。

請注意,此答案是 WIP,請隨時提出任何建議。

我陷入了同樣的問題,我目前正在嘗試使單元測試文檔中的所有測試都通過,但到目前為止我還停留在用戶測試中。 這是我的設置:

./tests/app.test.js

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(); 應該破壞連接上下文並防止此問題,但我無法使其工作。

./tests/helpers/strapi.js

讓實例;

async function setupStrapi() {
  if (!instance) {
    await Strapi().load();
    instance = strapi;
    await instance.server.mount();
  }
}

module.exports = { setupStrapi };

./tests/hello/index.js

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM