question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

My request is not intercepted/mocked in NodeJS (tests) If this doesn’t look right

See original GitHub issue

Environment

Name Version
msw ^0.21.2
node 12.12.0
OS 10.15.7 (Catalina)

Request handlers

// Example of declaration. Provide your code here.
import { setupServer } from 'msw/node'
import { rest } from 'msw'

const server = setupServer(
  rest.get(`${API_URL}/brands?query=""`, (req, res, ctx) => {
    return res(
      ctx.json({
        cursor: "super-cursor",
        data: [
          { id: 1, title: "Lu" },
          { id: 2, title: "Milka" },
        ],
      })
    );
  })
);

beforeAll(() => {
  server.listen();
  setToken("fakeToken");
});
afterEach(() => server.resetHandlers());
afterAll(() => {
  server.close();
  deleteToken();
});

describe("my test", () => {

   it("should render 'no data' text when list of item is empty", async () => {
      server.use(
        rest.get(`${API_URL}/brands?query=""`, (req, res, ctx) => {
          return res(
            ctx.json({
              cursor: "super-cursor",
              data: [],
            })
          );
        })
      );

      render(<BrandView />);

      await waitFor(() => {
        expect(screen.getByText("No Data")).toBeInTheDocument();
      });
    });

    it("should pop the error message when request failed", async () => {
      const message = "Something happen!";
      server.use(
        rest.get(`${API_URL}/brands?query=""`, (_, res, ctx) => {
          return res(ctx.json({ message }));
        })
      );

      render(<BrandView />);

      await waitFor(() => {
        expect(screen.getByText(message)).toBeInTheDocument();
      });
    });

})

Actual request

return await fetch(`${API_URL}/brands?query=${query}`, {
    headers: {
      ...headers,
      Authorization: `Bearer ${token}`,
    },
  }).then((data) => data.json());

Current behavior

My second test fails. The UI’s behavior is the same as the first test. Maybe there is an overlap? It’s like the second test was run with the first mock.

Expected behavior

My second test should be run with the second mock.

Screenshots

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
tony-gocommented, Dec 1, 2020

@kettanaito thanks ^^

0reactions
kettanaitocommented, Dec 1, 2020

@tony-go, I’ve moved your test into a reproduction repository with a minimal UI logic around it. Both tests pass rendering the correct result, applying the runtime handler.

Please use that repo as a reference to investigate further. I’m closing this, as there is no evident issue on MSW side.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Nodejs Test not erroring out inside Promise - Stack Overflow
In order for asynchronous spec to make use of existing promise, it should be returned from the spec: it('should receive expected response ...
Read more >
Test runner | Node.js v19.3.0 Documentation
If a directory named test is encountered, the test runner will search it recursively for all all .js , .cjs , and .mjs...
Read more >
Testing Error Handling in node.js | by Lars Trieloff
The example above shows a simple test that simulates an error 504, which can occur when the backend is overloaded. Proper client code...
Read more >
How To Test a Node.js Module with Mocha and Assert
We now have a basic TODO manager that we can experiment with. Next, let's manually test our code to see if the application...
Read more >
A Node.js Guide to Actually Doing Integration Tests - Toptal
However, your application is larger than that small chunk of code and almost no part of your application works in isolation. This is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found