Ant Design Pro V5

1 Cannot find module '@/components/Footer' from 'src/pages/user/Login/index.jsx'

jest.config.js加上moduleNameMapper可解决。

参考:https://stackoverflow.com/questions/42629925/testing-with-jest-and-webpack-aliases

2 window.matchMedia is not a function

testssetupTests.js需要加代码

```javascript
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
```

参考:https://stackoverflow.com/questions/39830580/jest-test-fails-typeerror-window-matchmedia-is-not-a-function

3 expect(...).toBeInTheDocument is not a function

需要jsdom环境,默认的node环境跑不了这个方法。

testssetupTests.js

```javascript
// do some test init
// react-testing-library 将您的组件显示为document.body,
// 这将为 jest-dom 添加一个自定义断言
import '@testing-library/jest-dom';
```

参考:https://stackoverflow.com/questions/56547215/react-testing-library-why-is-tobeinthedocument-not-a-function

4 The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/en/configuration#testenvironment-string. Consider using the "jsdom" test environment.

需要jsdom环境。且对应文件的测试脚本需要用注释声明使用jsdom。

srcpagesWelcome.test.js加以下代码:

```javascript
/**
* @jest-environment jsdom
*/
```

5 [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

@umijs/plugin-locale插件和jest不兼容。

6 TypeError: Cannot read property '@@initialState' of undefined

@umijs/plugin-initial-state插件和jest不兼容。

原文地址:https://www.cnblogs.com/foxcharon/p/14988101.html