我目前正在开始学习如何在React中编写测试,并且面临使我的IDE(Webstorm)识别我的.test.js
文件并显然识别出jest
本身的问题。
[在我的课程中,是2017年的课程,我了解到jest
将在我的package.json
文件中设置,因为它是react-create-app
library
的一部分。开始跟进课程模块时,我没有确定安装在package.json
部分内部"dependencies"
文件中的依赖项。
然后我安装了jest
以及下面列出的以下依赖项:
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"react-test-render": "^1.1.2",
"enzyme-to-json": "^3.4.4",
第一个问题是依赖冲突,这破坏了我的应用程序。似乎jest
的最新版本react-scrips
不接受3.4.1
的最新版本。因此,我不得不将jest
版本降级为24.9.0
,以便在开发模式下再次运行我的应用。
然后,我创建了一个文件来学习我的第一个测试技能,并且我注意到describe()
根本未被识别。
我不知道该怎么做才能使其正常工作。我不知道这是否也是编写测试的最佳设置,因为这是2017年的React
课程。
请查看我的package.json
文件:
{
"name": "veggie-burguers",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.2",
"enzyme-to-json": "^3.4.4",
"jest": "^24.9.0",
"prop-types": "^15.7.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-redux": "^7.2.0",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"react-test-render": "^1.1.2",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
运行yarn test
后,我遇到两个错误:
1st-
Could not find "store" in the context of "Connect(withRouter(App))". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(withRouter(App)) in connect options.
4 |
5 | test('renders learn react link', () => {
> 6 | const { getByText } = render(<App />);
| ^
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
问题:我还应该在App.test.js
文件中设置redux吗?这一切都已设置并在我的root
index.js
文件中运行
第二-
react-scripts test
FAIL src/components/Navigation/NavigationItems/NavigationItem/NavigationItems.test.js
● Test suite failed to run
Your test suite must contain at least one test.
我上面提到的test
文件,即NavigationItems.test.js
确实是空的,因为很明显IDE
甚至在我编写jest
时都无法识别其中的describe()
,因此它将功能指为unresolved
。
如果需要更多信息,我将相应地更新此查询。
问题是Webstorm无法识别我的... jest
文件中的test
。因此,由于这个原因,我在这里更改了问题的标题,与IDE
相关。
解决方案:
在Webstorm中=>首选项=>语言和框架=> JavaScript =>库,按Download...
,从可用存根列表中选择'jest'
,按下载并安装。
此后,玩笑被正确识别,我可以使用其功能。