简体   繁体   中英

Mock Service Worker / Node isn't working and I can't see why

If anyone can spot whatever's wrong with this code, I'd really appreciate. Not seeing an issue myself, but it's failing.

import React from "react"
import {setupServer} from "msw/node"
import {rest} from "msw"

describe("mocking apis", () => {
  const testCall = jest.fn()
  const server = setupServer(
    ...[
      rest.get("/test", (req, res, ctx) => {
        console.log('This line is never run')
        testCall()
        return res(ctx.json({message: "success"}))
      }),
    ]
  )

  test("test", async () => {
    server.listen()
    fetch("/test", {method: "GET"})
    expect(testCall).toHaveBeenCalled()
    server.close();
  })
})

I also had this problem. After a while I realized the cause. In my src/setupTests.js file I had:

import { enableFetchMocks } from 'jest-fetch-mock';
...
enableFetchMocks();

So, fetch() was not being called at all.

I made 3 changes to the posted code to get it to work:

  1. Import and call disableFetchMocks() .
  2. Add await before fetch(... .
  3. Change the URL to http://localhost/test , to address a test error that said I needed to use an absolute URL.

Here is the working code (cleaned up to AirB&B style by PyCharm):

import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { disableFetchMocks } from 'jest-fetch-mock';

describe('mocking apis', () => {
  const testCall = jest.fn();
  const server = setupServer(
    ...[
      rest.get('http://localhost/test', (req, res, ctx) => {
        console.log('This line is run');
        testCall();
        return res(ctx.json({ message: 'success' }));
      }),
    ],
  );

  test('test', async () => {
    disableFetchMocks();
    server.listen();
    await fetch('http://localhost/test', { method: 'GET' });
    expect(testCall).toHaveBeenCalled();
    server.close();
  });
});

When you run your tests these run in a node environment, in this fetch function does not exist (it means: global.fetch) for that reason you need to make a polyfill.

I recommend installing the npm package 'whatwg-fetch'

npm install whatwg-fetch

and use it like this:

import 'whatwg-fetch';

This video could help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM