What's the best way to reset the MockPool between tests? #3619
-
I have a scenario where two tests use the same What’s the best way to avoid this? I thought about re-creating the EDIT: the scenario described above is just an example. What I want to know is how to handle unconsumed interceptors left over by previous tests. Example: const { MockAgent, setGlobalDispatcher, request } = require("undici");
const { before, after, it } = require("node:test");
const assert = require("node:assert");
const mockAgent = new MockAgent({
keepAliveTimeout: 10,
keepAliveMaxTimeout: 10,
});
const interceptor = mockAgent.get("http://localhost");
setGlobalDispatcher(mockAgent);
before(() => {
mockAgent.disableNetConnect();
});
after(() => {
mockAgent.enableNetConnect();
mockAgent.close();
});
it("test A", async () => {
interceptor
.intercept({
path: "/path-a",
method: "GET",
})
.reply(200, { foo: "baz" });
interceptor
.intercept({
path: "/path-b",
method: "GET",
})
.reply(200, { hello: "world" });
let responseA = await request("http://localhost/path-a");
responseA = await responseA.body.json();
assert.equal(responseA, { foo: "bar" }); // throws
// won't run
let responseB = await request("http://localhost/path-b");
responseB = await responseB.body.json();
assert.equal(responseB, { hello: "world" });
});
it("test B", async () => {
interceptor
.intercept({
path: "/path-b",
method: "GET",
})
.reply(200, { dog: "cat" });
let response = await request("http://localhost/path-b");
response = await response.body.json();
// i'm expecting this to be true, but it won't as there's an unconsumed
// interceptor from test A and will return { hello: "world"}
assert.equal(response, { dog: "cat" });
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I'd recommend to not re-use the mocks across test scenarios but isolate each scenario, and individually assign their mocks, so scenarios like this can be avoided. Having global shared mocks (almost) always lead to hard to solve inconsistencies |
Beta Was this translation helpful? Give feedback.
I'd recommend to not re-use the mocks across test scenarios but isolate each scenario, and individually assign their mocks, so scenarios like this can be avoided.
Having global shared mocks (almost) always lead to hard to solve inconsistencies