我正在使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0测试React组件.
该组件已呈现一个按钮:
<button
type="button"
className="btn btn-lg btn-primary btn-danger"
disabled={this.state.cancelButtonDisabled}
onClick={() => this.handleCancel()}
ref="cancelButton"
>Cancel</button>);
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我正在渲染组件:
const component = renderer.create(
<MyComponent />
);
const instance = component.getInstance();
// This works but is ugly
component.toJSON().children[1].children[0].props.onClick();
// This doesn't work
ReactTestUtils.Simulate.click(instance.refs.cancelButton);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)
模拟点击此按钮的推荐方法是什么?您可以遍历组件的JSON表示,但看起来它们应该是更好的方法.
在我使用ReactTestUtils.renderIntoDocument之前,您可以使用refs将组件的引用传递给ReactTestUtils.Simulate.click
我已经看到了这个问题 - 如何与ReactTestRenderer/Jest呈现的组件进行交互,但我认为API已经改变,因为我的组件实例没有find()方法.
我在使用ES6编写的Jest(v16.0.1)测试测试使用Typescript(v2.0.3)编写的React组件时遇到了一些问题.
我正在使用ts-jest(v0.1.8)预处理器和package.json的相关部分看起来像
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
]
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行测试时,我得到:
FAIL app/components/__tests__/TestTotalNumberOfTeapots.js
? Test suite failed to run
/Users/aaron/Desktop/teabot_stats/app/components/__tests__/TestTotalNumberOfTeapots.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.673s
Ran all test suites.
Run Code Online (Sandbox Code Playgroud)
我的测试看起来像
import React from 'react';
import TotalNumberOfTeapots from '../TotalNumberOfTeapots.tsx';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<TotalNumberOfTeapots numberOfTeapots='1' /> …Run Code Online (Sandbox Code Playgroud)