我第一次尝试编写用于本机反应的单元测试用例。.我遇到以下错误
AlbumDetailView.js
import { View, Image } from 'react-native';
import { Button, Provider, Text } from 'react-native-paper';
import React from 'react';
import styles from '../style/AlbumDetailView.component.style';
export default class DetailView extends React.Component {
static navigationOptions = {
title: 'Album Details',
};
render() {
{ /* Using the navigation prop we can get the value passed from the previous screen */ }
const { navigation } = this.props;
const albumTitle = navigation.getParam('albumTitle', 'Default data');
const albumImg = navigation.getParam('albumImg', 'some default value');
const goBackToHome = () => this.props.navigation.goBack(this.props.navigation.state.key);
return (
<React.Fragment>
<Provider>
<View style={styles.mainContainer}>
<View style={styles.albumViewContainer}>
<Image source = {{ uri: albumImg }} style={styles.imageView} />
<Text style={styles.textStyle}>{albumTitle}</Text>
<Button mode="contained"
onPress={() => this.props.navigation.navigate('HomeScreen', { goBackToHome, })}
style={styles.buttonStyle} testID='HomeButton'>
HOME
</Button>
</View>
</View>
</Provider>
</React.Fragment>
);
}
}
我正在编写与以下相同的测试用例
import 'react-native';
import React, { Component } from 'react';
import { shallow } from 'enzyme';
import AlbumDetailsView from '../component/AlbumDetailsView';
describe('Album Details Screen', () => {
it('should render Album Details component', () => {
const wrapper = shallow(<AlbumDetailsView />);
});
it('should render initial layout', () => {
// when
const component = shallow(<AlbumDetailsView />);
// then
expect(component.getElements()).toMatchSnapshot();
});
it('should check if BackButton exists', () => {
const wrapper = shallow(<AlbumDetailsView />);
wrapper.findWhere(n => n.name() === 'Button' && n.prop('testID') === 'HomeButton')
});
});
我可以知道如何处理吗?
答案 0 :(得分:2)
您需要在测试中模拟navigation
道具。当然getParam
是未定义的,因为您尚未在测试中通过它。 react-navigation
在运行应用程序时会自动传递,但是在测试中,您必须手动对其进行模拟。
it('should render Album Details component', () => {
const wrapper = shallow(
<AlbumDetailsView navigation={{ getParam: jest.fn() }} />
);
});
现在getParam
将不再undefined
。当然,使用上述代码,在调用getParam('albumTitle')
时不会返回任何内容,因为在测试中getParam()
只是一个jest.fn()
,它可以转换为不执行任何操作的空函数。 / p>
如果要使其返回值,则还必须手动实现模拟函数,例如
it('should render Album Details component', () => {
const wrapper = shallow(
<AlbumDetailsView navigation={{ getParam: (param) => {
if (param === 'albumTitle') return 'albumTitle';
...
} }} />
);
});
答案 1 :(得分:0)