What is the best way to mock bypassed fetch in handlers? #1023
-
Hello 👋🏻 I do some clean-up logic to not-mocked endpoint in my handler and that causes some troubles for me in tests. What is the best way to avoid hitting dead service in my test? example: rest.delete("/api/blocks/:id", async (req, res, ctx) => {
const block = blocksMap.get(req.params.id);
if (block.kind === "view") {
await api.deleteEntities([{id: block.content.id}]);
// ❗ catch to avoid failed test
.catch((err) => console.warn("[handlers]: Can't delete entity", err));
}
if (block.kind === "rich-text") {
await api.deleteDocuments([{id: block.content.id}])
// ❗ catch to avoid failed test
.catch((err) => console.warn("[handlers]: Can't delete document", err));
}
blocksMap.delete(req.params.id);
return res(ctx.json({success: true}));
}), Overriding delete endpoint in each test could be an option but then I need to give tests access to edit mocked db |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hey, @MikeYermolayev. I recommend not performing any bypassed requests during your tests. There's no reason to: the entire purpose of API mocking is to scope your testing surface to the code/logic you wish to test. Performing an actual request subjects your test runs to all sorts of brittle network behaviors and results in unreliable tests. The library comes with a built-in way to prevent such bypassed requests from happening during test runs: server.listen({ onUnhandledRequest: 'error' }) With this option set, whenever there's a request you don't wish to handle, it will throw an exception, halting your test. This is the behavior I'd recommend. If you wish to mock certain endpoints that don't have any implementation, you can respond with a 501 status code (to stay semantically correct), or a dummy 200 (but this will have implications, though). Feel free to clarify what's your expected behavior here in the case I didn't understand it. |
Beta Was this translation helpful? Give feedback.
Hey, @MikeYermolayev.
I recommend not performing any bypassed requests during your tests. There's no reason to: the entire purpose of API mocking is to scope your testing surface to the code/logic you wish to test. Performing an actual request subjects your test runs to all sorts of brittle network behaviors and results in unreliable tests.
The library comes with a built-in way to prevent such bypassed requests from happening during test runs:
With this option set, whenever there's a request you don't wish to handle, it will throw an exception, halting your test. This is the behavior I'd recommend.
If you wish to mock certain endpoints that d…