React native React Native/Jest TypeError:无法读取属性';参数';使用jest进行未定义的测试
我正在尝试使用jest在应用程序中创建一个测试,以下是我的代码行:React native React Native/Jest TypeError:无法读取属性';参数';使用jest进行未定义的测试,react-native,jestjs,react-native-navigation,React Native,Jestjs,React Native Navigation,我正在尝试使用jest在应用程序中创建一个测试,以下是我的代码行: import React, { Component } from 'react'; import {...} from 'react-native'; import jwt_decode from 'jwt-decode'; class CreateProduct extends Component { constructor(props) { super(props); this.keyboardHeight = n
import React, { Component } from 'react';
import {...} from 'react-native';
import jwt_decode from 'jwt-decode';
class CreateProduct extends Component {
constructor(props) {
super(props);
this.keyboardHeight = new Animated.Value(0);
this.imageHeight = new Animated.Value(199);
this.state = {
isButtonsHidden: false,
title: '',
price: '',
description: '',
isDialogVisible: false,
messageError: '',
};
}
_goBack = async () => {
const {state} = this.props.navigation;
var token = state.params ? state.params.token : undefined;
this.props.navigation.navigate('MyProducts', {token:token});
}
我想测试导航:
this.props.navigation.navigate('MyProducts', {token:token});
现在,这是测试的尝试:
describe('Testing navigation', () =>{
let wrapper = null
const spyNavigate = jest.fn()
const props = {
navigation:{
navigate: spyNavigate
}
}
const params = {
token: 'randomToken'
}
beforeEach(() => {
wrapper = shallow(<CreateProduct {...props}/>)
wrapper.setState({params: params})
})
it('should test navigation', () => {
wrapper.instance()._goBack(params)
expect(spyNavigate).toHaveBeenCalled()
})
})
description('测试导航',()=>{
设wrapper=null
const spyNavigate=jest.fn()
常量道具={
导航:{
导航:spyNavigate
}
}
常量参数={
令牌:“随机令牌”
}
在每个之前(()=>{
包装器=浅()
wrapper.setState({params:params})
})
它('应该测试导航',()=>{
wrapper.instance()。\u goBack(参数)
expect(spyNavigate).toHaveBeenCalled()
})
})
但是我收到了
我假设传递常量参数的方式有错误。你能帮我告诉我什么是最好的方式,我可以这样做,以模拟一个令牌,我可以在屏幕上导航
谢谢。根本原因是您的\u goBack
是异步的。但在运行expect
之前,不要等到它结束。更重要的是:jest也不会等待\u goBack
完成,所以您甚至不会看到错误
无法读取未定义的属性“params”
这是因为您没有在navigation.params
中模拟状态
使用异步代码有:从it()
返回承诺或手动运行done()
回调(它作为it()
中的第一个参数传递)
我将选择第二个,因为它允许我们在运行expect
之前等待goBack
完成:
describe('Testing navigation', () => {
let wrapper = null
const spyNavigate = jest.fn()
const props = {
navigation: {
navigate: spyNavigate,
state: {}
}
}
const params = {
token: 'randomToken'
}
beforeEach(() => {
wrapper = shallow(<CreateProduct {...props} />)
wrapper.setState({ params: params })
})
it('should test navigation', async () => {
await wrapper.instance()._goBack(params)
expect(spyNavigate).toHaveBeenCalled()
})
})
那看起来很乱
或者使用done()
callback
it('should test navigation', (done) => {
wrapper.
instance()._goBack(params).
then(() => expect(spyNavigate).toHaveBeenCalled()).
then(done);
})
it('should test navigation', (done) => {
wrapper.
instance()._goBack(params).
then(() => expect(spyNavigate).toHaveBeenCalled()).
then(done);
})