Skip to content

UI Testing Annex

To use msw to mock API call in Jest with create-react-app

  1. run npm i msw undici
  2. add the following to package.json

  "jest": {
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+[^esm]\\.(js|jsx|mjs|cjs|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ]
  }
3. add the following file src/jest.polyfills.js

// jest.polyfills.js
/**
 * @note The block below contains polyfills for Node.js globals
 * required for Jest to function when running JSDOM tests.
 * These HAVE to be require's and HAVE to be in this exact
 * order, since "undici" depends on the "TextEncoder" global API.
 *
 * Consider migrating to a more modern test runner if
 * you don't want to deal with this.
 */

const { TextDecoder, TextEncoder } = require('node:util')
const { ReadableStream } = require('node:stream/web')
const { clearImmediate } = require('node:timers') 
const { performance } = require('node:perf_hooks')

Object.defineProperties(globalThis, {
  TextDecoder: { value: TextDecoder },
  TextEncoder: { value: TextEncoder },
  clearImmediate: { value: clearImmediate },
  performance: { value: performance },
  ReadableStream: { value: ReadableStream }
})

const { Blob, File } = require('node:buffer')
const { fetch, Headers, FormData, Request, Response } = require('undici')

Object.defineProperties(globalThis, {
  fetch: { value: fetch, writable: true },
  Blob: { value: Blob },
  File: { value: File },
  Headers: { value: Headers },
  FormData: { value: FormData },
  Request: { value: Request },
  Response: { value: Response },
})
4. add the following file src/setupTests.js

import '@testing-library/jest-dom';
import "./jest.polyfills";