facebook / create-react-app

Set up a modern web app by running one command.
https://create-react-app.dev
MIT License
102.78k stars 26.87k forks source link

How can I configure react-scripts jest to mock the return of an endpoint? #12730

Open caio-borghi-yapi opened 2 years ago

caio-borghi-yapi commented 2 years ago

I'm trying to use a custom configuration for jest by running this command

react-scripts test -- --config=jest.config.js

jest.config.js
/* eslint-disable no-undef */
module.exports = {
 setupFilesAfterEnv: ['<rootDir>/jestSetup.js'],
 preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.ts?$': 'ts-jest',
  },
  transformIgnorePatterns: ['<rootDir>/node_modules/'],
}
jestSetup.js

const { server } = require('./src/app/mocks/api/server')
const AbortController = require('abort-controller')
const { fetch, Headers, Request, Response } = require('cross-fetch')

// Establish API mocking before all tests.
beforeAll(() => {
  server.listen()
})

// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers())

// Clean up after the tests are finished.
afterAll(() => server.close())

global.fetch = fetch
global.Headers = Headers
global.Request = Request
global.Response = Response
global.AbortController = AbortController
isqua commented 2 years ago

AFAIK, neither react-scripts nor jest do the network request mocks. Have you tried some third-party libraries like nock or msw?