create-react-app 如何配置react-scripts jest来模拟端点的返回?

zysjyyx4  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(59)

我正在尝试使用自定义配置来运行jest,通过运行以下命令:
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
vwkv1x7d

vwkv1x7d1#

据我所知,react-scripts和jest都不会进行网络请求的模拟。你尝试过一些第三方库,如nockmsw吗?

相关问题