Ant Design Pro V5 - jest 單元測試踩坑記錄


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

tests\setupTests.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環境跑不了這個方法。

tests\setupTests.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。

src\pages\Welcome.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不兼容。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM