I have this code to mock the data response from the API but somehow, the 2nd test is always overwritten by the first one and leads to a test failure. Even using res.once
not working.
// ...import section
test('Should component render successfully', () => {
server.use(
rest.get(
`${process.env.REACT_APP_API_ENDPOINT}/api/discount`,
(req, res, ctx) => {
return res(ctx.status(200), ctx.json({ data: DiscountMockData.vouchers[0] }));
}
)
);
render(<MyComponent />);
expect(screen.getByTestId('result')).toBeInTheDocumment();
});
test('Should component render failed because of API response', () => {
server.use(
rest.get(
`${process.env.REACT_APP_API_ENDPOINT}/api/discount`,
(req, res, ctx) => {
return res(ctx.status(400), ctx.json({}));
}
)
);
render(<MyComponent />);
expect(screen.getByTestId('error')).toBeInTheDocumment();
})
Somehow, the Should component render failed because of API response
always failed because the response is success on the first test, if I remove the first test then the 2nd is working.
Any idea?