我正在尝试快照测试这段代码:
import 'react-native';
import React from 'react';
import TestComponent from './TestComponent';
import renderer from 'react-test-renderer';
describe('TestComponent', () => {
const asset = {
type: 'car',
}
it('renders correctly', () => {
const tree = renderer.create(
<TestComponent
asset={asset} />
).toJSON();
expect(tree).toMatchSnapshot();
});
})
我的测试现在看起来像这样:
TypeError: Cannot read property '_tag' of undefined
我的问题是我得到了:
jest.mock('Picker', () => 'Picker')
我认为我应该基于this issue
来嘲笑它我试过简单地添加:
Invariant Violation: Element type is invalid: expected a string (for built-
in components) or a class/function (for composite components)
but got: undefined. Check the render method of `TestComponent`.
但是它仍然会引发错误,因为Picker.Item仍未被模拟
jest.mock('Picker', () => {return {Item: 'Item'}});
----------------------------------------------------
class Picker{
Item = 'PickerItem'
}
jest.mock('Picker', () => {
return Picker;
});
我试过的其他变种无济于事:
const gulp = require('gulp');
const markdownToJSON = require('gulp-markdown-to-json');
const marked = require('marked');
marked.setOptions({
pedantic: true,
smartypants: true
});
gulp.task('markdown', () => {
gulp.src('./content/**/*.md')
.pipe(markdownToJSON(marked))
.pipe(gulp.dest('.'))
});
答案 0 :(得分:6)
也创建了一个github issue,这是一个有效的答案:
jest.mock('Picker', () => {
const Picker = class extends Component {
static Item = props => React.createElement('Item', props, props.children);
static propTypes = { children: React.PropTypes.any };
render() {
return React.createElement('Picker', this.props, this.props.children);
}
}
return Picker;
})
答案 1 :(得分:1)
对于Expo 39,我可以通过将以下模拟添加到我的测试/设置文件中来测试@react-native-community/picker
:
jest.mock('@react-native-community/picker', () => {
const React = require('React')
const RealComponent = jest.requireActual('@react-native-community/picker')
class Picker extends React.Component {
static Item = (props: { children: never }) => {
return React.createElement('Item', props, props.children)
}
render () {
return React.createElement('Picker', this.props, this.props.children)
}
}
Picker.propTypes = RealComponent.propTypes
return {
Picker
}
})
请注意,@react-native-community/picker
现在是react-native-picker/picker。