我正在尝试快照测试这段代码:
import React, { Component } from 'react';
import {
Picker,
} from 'react-native';
export default class TestComponent extends Component {
render() {
return (
<Picker
selectedValue={this.props.asset.type}
onValueChange={this.props.onTypeChange}>
<Picker.Item label="Type of asset" value="default" />
<Picker.Item label="Car" value="car" />
<Picker.Item label="Boat" value="boat" />
<Picker.Item label="Ship" value="ship" />
</Picker>
);
}
}
我的测试现在是这样的:
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')
但是它仍然抛出一个错误,因为Picker。项目仍未被模拟
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`.
我尝试了其他没有效果的变体:
jest.mock('Picker', () => {return {Item: 'Item'}});
----------------------------------------------------
class Picker{
Item = 'PickerItem'
}
jest.mock('Picker', () => {
return Picker;
});
创建了一个github问题,这里是一个工作的答案:
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;
})
对于Expo v39,我可以通过在测试/设置文件中添加以下模拟来测试@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。
https://jestjs.io/docs/en/tutorial-react-native提示