[英]Unable to run jest test case
我寫了一個小的測試用例來測試ThankYouPage組件,如下所示
import ToggleDisplay from 'react-toggle-display';
import styles from '../styles.css';
function ThankYouPage(props) {
return (
<ToggleDisplay show={props.show}>
<div className={styles.thankyouText}> Thank you!</div>
<div className={styles.helpText}>
The more you thanks, the better.
</div>
</ToggleDisplay>
);
}
export default ThankYouPage;
以下是開玩笑的測試用例-
import React from 'react';
import ThankYouPage from './components/thank-you-page';
import { shallow } from 'enzyme';
describe('<ThankYouPage />', () => {
it('renders 1 ThankYouPage component', () => {
const component = shallow(<ThankYouPage show=true />);
expect(component).toHaveLength(1);
});
});
以下是運行npm test
后在控制台上獲得的跟蹤
> myreactapp@1.0.0 test /Users/rahul/myreactapp
> jest
FAIL tests/thank-you-page.test.js
● Test suite failed to run
/Users/cominventor/myreactapp/tests/thank-you-page.test.js: Unexpected token (8:30)
6 | describe('<ThankYouPage />', () => {
7 | it('renders 1 ThankYouPage component', () => {
> 8 | const component = shallow(<ThankYouPage show=true />);
| ^
9 | expect(component).toHaveLength(1);
10 | });
11 | });
我是否缺少淺淺解釋jsx的依賴項? 以下是我的部門長的樣子
"devDependencies": {
"babel-jest": "^22.4.3",
"oc-template-react-compiler": "5.0.2",
"prettier": "^1.10.2",
"prettier-eslint": "^8.8.1"
},
"dependencies": {
"axios": "^0.18.0",
"enzyme": "^3.3.0",
"jest": "^22.4.3",
"jsdom": "^11.10.0",
"querystring": "^0.2.0",
"react-cookie": "^2.1.4",
"react-scripts": "^1.1.4",
"react-toggle-display": "^2.2.0"
}
嘗試安裝
npm i --save-dev enzyme enzyme-adapter-react-16
將transform-class-properties添加到.babelrc文件,如下所示-
"plugins": [
"transform-class-properties"
]
將以下內容添加到package.json的頂層
"jest": {
"moduleNameMapper": {
"\\.(css)$": "jest-css-modules"
}
接下來的單元測試應該可以正常工作。
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import ThankYouPage from './components/thank-you-page';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
describe('<ThankYouPage />', () => {
it('renders 1 ThankYouPage component', () => {
const component = shallow(<ThankYouPage show=true />);
expect(component).toHaveLength(1);
});
});
嘗試這個:
import * as React from 'react';
import * as Adapter from 'enzyme-adapter-react-16';
import {shallow, configure} from 'enzyme';
import ThankYouPage from './components/thank-you-page';
configure({adapter: new Adapter()});
describe('my test', () => {
...
...
});
從npm安裝enzyme-adapter-react-16
軟件包。
您以錯誤的方式(而不是相對路徑)導入了酶,請嘗試import { shallow } from 'enzyme';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.