You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Strapi单元测试问题:strapi.server.httpServer无法正常工作

问题:Strapi测试环境中接口返回404错误

问题背景

在新的TypeScript版Strapi应用中按官方文档搭建测试环境后,第一个测试strapi is defined可通过,但测试自定义接口/api/hello时返回404错误;直接使用运行中的Strapi地址http://127.0.0.1:1337测试该接口则正常。

辅助文件(helpers/strapi.js)

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
    });
});

错误信息

expected 200 "OK", got 404 "Not Found"

解决方案

问题根源是测试环境中Strapi的路由未被正确初始化:默认的instance.server.mount()仅挂载了服务器,但未启动完整的路由系统和中间件链。

方案一:启动完整Strapi服务

修改setupStrapi函数,将instance.server.mount()替换为instance.server.start(),确保Strapi所有组件(路由、中间件、插件)正确初始化:

async function setupStrapi() {
  if (!instance) {
    instance = await Strapi().load();
    await instance.server.start(); // 启动完整服务,自动注册路由
  }
  return instance;
}

方案二:手动注册路由(不推荐)

若不想启动完整服务,可手动触发路由注册,但这种方式易遗漏依赖组件,稳定性较差:

async function setupStrapi() {
  if (!instance) {
    instance = await Strapi().load();
    await instance.server.mount();
    // 手动合并API路由与中间件
    instance.server.routes = instance.server.routes.concat(instance.api.routes);
    instance.server.middlewares = instance.server.middlewares.concat(instance.api.middlewares);
    await instance.server.compile();
  }
  return instance;
}

推荐使用方案一,确保测试环境与生产环境的行为一致。

内容的提问来源于stack exchange,提问作者Tochie Sol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:01:13