我想知道用jest在expressJS中测试多条路由的最佳方法。
我目前的问题是,当我尝试测试多个路由使用相同的模拟函数,最后一个路由抛出一个未定义的错误。
下面是代码中的上下文。
app.ts
import * as express from "express";
import controllerOne from "./controllers/one";
import controllerTwo from "./controllers/two";
const app = express();
app.use("/one", controllerOne);
app.use("/two", controllerTwo);
export default app;
控制器/one.ts
import getDbConnection from "../db";
import * as express from "express";
const router = express.Router();
const db = getDbConnection();
router.get("/", async (_, res) => {
const sql = "SELECT * from table";
const result = await db.query(sql);
res.status(200).json(result);
});
export default router;
控制器/two.ts
import getDbConnection from "../db";
import * as express from "express";
const router = express.Router();
const db = getDbConnection();
router.get("/", async (_, res) => {
const sql = "SELECT * from table";
const result = await db.query(sql);
res.status(200).json(result);
});
export default router;
测试/one.ts
import * as request from "supertest";
import { mocked } from "ts-jest/utils";
import db from "../db";
jest.mock("../db");
const mockedDB = mocked(db);
const data = ["data"];
describe("Controller One", () => {
afterAll(() => {
jest.restoreAllMocks();
jest.resetModules();
});
beforeEach(() => {
const mockedQueryFn = {
query: jest.fn().mockResolvedValueOnce(data),
};
mockedDB.mockReturnValueOnce(mockedQueryFn);
});
it("should retrieve one", async () => {
const mod = require("../src/app");
const app = (mod as any).default;
await request(app)
.get("/one")
.expect(200)
.expect(function (res) {
expect(res.body).toEqual(data);
});
});
});
测试/two.ts
import * as request from "supertest";
import { mocked } from "ts-jest/utils";
import db from "../db";
jest.mock("../db");
const mockedDB = mocked(db);
const data = ["data"];
describe("Controller One", () => {
afterAll(() => {
jest.restoreAllMocks();
jest.resetModules();
});
beforeEach(() => {
const mockedQueryFn = {
query: jest.fn().mockResolvedValueOnce(data),
};
mockedDB.mockReturnValueOnce(mockedQueryFn);
});
it("should retrieve one", async () => {
const mod = require("../src/app");
const app = (mod as any).default;
await request(app)
.get("/two")
.expect(200)
.expect(function (res) {
expect(res.body).toEqual(data);
});
});
});
现在我的问题是如果我运行测试,测试/1。t会通过测试2。ts将失败,错误TypeError: Cannot read property 'query' of undefined
引用这行const result = await db.query(sql)
切换控制器导入时
import controllerTwo from "./controllers/two";
import controllerOne from "./controllers/one";
则test/two.ts
通过,test/one.ts
失败,错误相同。我还想提到,有/没有重置jest mock,我得到相同的结果。
这可能与您在测试结束时没有调用done这一事实有关。在测试的expect部分中,调用done()
。您还需要更改回调,使其像这样:
it("should retrieve one", async (done) => {