reactjsjestjsmsw

ReactJS msw data response for each test weird overlap


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?


Solution

  • import { cleanup } from "@testing-library/react";
    import { setupServer } from "msw/node";
    
    
    const handlers = [
      rest.get(URL, (req, res, ctx) => {
        // ...
        return response;
      }),
      // so on ...
    ];
    const server = setupServer(...handlers);
    
    
    // Cleanup after each test case
    afterEach(() => {
      cleanup();
      server.resetHandlers();
    });
    
    
    afterAll(() => {
      server.close();
    });