Jest.js Strapi单元测试:strapi.server.httpServer不工作

yyhrrdl8  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(52)

我在一个新的strapi应用程序(Typescript)上设置了一个测试环境,遵循文档中的示例-https://docs.strapi.io/dev-docs/testing#install-test-tools。
这是我的帮助文件,如docs示例中所示:

const Strapi = require("@strapi/strapi");
const fs = require("fs");

let instance;

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

    await instance.server.mount();
  }
  return instance;
}

async function cleanupStrapi() {
  const dbSettings = strapi.config.get("database.connection");

  //close server to release the db-file
  await strapi.server.httpServer.close();

  // close the connection to the database before deletion
  await strapi.db.connection.destroy();

  //delete test database after all tests have completed
  if (dbSettings && dbSettings.connection && dbSettings.connection.filename) {
    const tmpDbFile = dbSettings.connection.filename;
    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
}

module.exports = { setupStrapi, cleanupStrapi };

字符串
这是我的测试文件:

const fs = require("fs");
const { setupStrapi, cleanupStrapi } = require("./helpers/strapi");
const request = require("supertest");

beforeAll(async () => {
  await setupStrapi();
}, 10000);

afterAll(async () => {
  await cleanupStrapi();
}, 10000);

it("strapi is defined", () => {
  expect(strapi).toBeDefined();
});

it("should return hello world", async () => {
  await request(strapi.server.httpServer)
    .get("/api/hello")
    .expect(200) // Expect response http code 200
    .then((data) => {
      expect(data.text).toBe("Hello World!"); // expect the response text
    });
});


当我运行这个测试时:
第一个测试通过-“strapi已定义”
但下面的第二个测试失败了。

it("should return hello world", async () => {
  await request(strapi.server.httpServer)
    .get("/api/hello")
    .expect(200) // Expect response http code 200
    .then((data) => {
      expect(data.text).toBe("Hello World!"); // expect the response text
    });
});


我得到这个错误:
第一个月
Error log
当我将strapi.server.httpServer替换为“http://127.0.0.1:1337“(指向正在运行的strapi应用程序)时,测试成功运行。
请问我需要做什么来解决这个问题?

bxgwgixi

bxgwgixi1#

/API/hello是一个自定义端点,您需要在控制器中实现它或跳过它。
https://docs.strapi.io/dev-docs/testing

相关问题