我第一次在React中使用jest,这次我在React Native项目中使用它。它与下面的代码完美地工作。
import React, { Component } from 'react';
import {
Text,
View,
} from 'react-native';
export default class Login extends Component {
render() {
return (
<View>
<Text>Login Page</Text>
</View>
)
}
}
但是在我的组件库中添加了一个按钮后,我的测试失败了。
import React, { Component } from 'react';
import {
Text,
View,
} from 'react-native';
import { Button } from 'tc-components';
export default class Login extends Component {
render() {
return (
<View>
<Text>Login Page</Text>
<View>
<Button onPress={this.loginHandler.bind(this)}>Log in</Button>
</View>
</View>
)
}
}
错误信息
- SyntaxError: Unexpected reserved word
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:306:10)
at Object.<anonymous> (app/scenes/Activity.js:2:17)
at Object.<anonymous> (__tests__/Activity-test.js:3:15)
1 test suite failed, 0 tests passed (0 total in 1 test suite, run time 1.261s)
需要在测试文件中手动模拟tc-component
jest.mock('tc-component', () => {
const React = require('react');
const TC = {}
const createComponent = (type) => {
return React.createClass({
displayName: type,
propTypes: {
children: React.PropTypes.node
},
render() {
return <div {...this.props}>{this.props.children}</div>;
}
});
};
TC.Button = createComponent("Button");
return TC;
});
import 'react-native';
import React from 'react';
import Activity from '../scenes/Activity';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
describe('Activity', () => {
it('renders correctly', () => {
const tree = renderer.create(
<Activity />
).toJSON();
expect(tree).toMatchSnapshot();
});
});