我的猜测是,“/test”端点在套件中的其他一些测试中被调用,您可以尝试使用
.only
甚至试图运行整个套件
serially
.
为了回答最初的问题,如果您正在运行特定的测试用例场景,或者您正在尝试运行整个套件,那么整个套件必须是孤立和一致的,因此您需要清除任何可能实际影响结果的遗留问题。
所以你可以实际使用
.beforeEach
或者
.beforeAll
方法,由Jest提供,以便“模拟”Redis和
.afterAll
清除方法。
伪实现如下所示:
import redis from "redis";
import redis_mock from "redis-mock";
import request from "supertest";
jest.mock("redis", () => jest.requireActual("redis-mock"));
// Client to be used for manually resetting the mocked redis database
const redisClient = redis.createClient();
// Sometimes order matters, since we want to setup the mock
// and boot the app afterwards
import app from "./app";
const COUNT = 3;
const testRequest = () => supertest(app).get("/test");
describe("testing", () => {
afterAll((done) => {
// Reset the mock after the tests are done
jest.clearAllMocks();
// You can also flush the mocked database here if neeeded and close the client
redisClient.flushall(done);
// Alternatively, you can also delete the key as
redisClient.del("test", done);
redisClient.quit(done);
});
it("dummy test to run", () => {
expect(true).toBe(true);
});
it("the actual test", async () => {
let last;
// Run the requests in serial
for (let i = 0; i < COUNT - 1; i++) {
last = await testRequest();
}
// assert the last one
expect(last.status).toBe(200);
expect(last.body.current).toBe(COUNT);
});
});