我编写了一个小测试用例来测试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"
}发布于 2018-05-11 10:43:20
试着安装
npm i --save-dev enzyme enzyme-adapter-react-16
向.babelrc文件添加transform-class-属性,如下所示-
"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);
});
});发布于 2018-05-11 10:47:22
试试这个:
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包。
发布于 2018-05-11 10:49:31
您以错误的方式(不是相对路径)导入酶,请尝试import { shallow } from 'enzyme';。
https://stackoverflow.com/questions/50290444
复制相似问题