首页 > 解决方案 > React Native Enzyme Jest props.onPress 不是函数

问题描述

在尝试编写测试时,如果我从孩子那里调用父函数,它会返回

props.onPress() 不是函数

我假设我需要在测试中手动传递道具以供按下时使用。但我觉得这可能会破坏测试代码结构中存在的内容的目的。

家长

export default class Parent extends React.Component {
   constructor(){
     super()
   }

   _method(){
     return "Something"
   }

   render(){
    return{
      <Child onPress={this._method.bind(this) }
    }
   }
}

孩子

export default (Child = (props) => {
   const _childMethod = () => {
     return props.onPress()
   }

   return{
     <View>
         <TouchableOpacity onPress={() => { return _childMethod() }}>

        </TouchableOpacity>
    </View>
   }

})

测试

import "react-native"
import React from "react"
import Enzyme, {shallow, render} from "enzyme"
import Parent from "path/to/parent"
import Child from "path/to/child"

Enzyme.configure({adapter: new Adapter()})
const wrapper = shallow(<Child />)

it("Should return something", () => {
  console.log(wrapper.props().onPress())
})

标签: react-nativejestjsenzyme

解决方案


你的代码有一些错误,首先return语句应该使用()而不是{}。如果在组件的 render 方法的 return 语句中使用 {},则会引发错误。

您正在测试它的道具是子组件 TouchableOpacity 的功能,而不是子组件的道具。

要正确测试它,您应该使用console.log(wrapper.props().children.props.onPress)

有了这个我得到了这个回应:

PASS  __tests__\dummy.test.js
  ● Console    
    console.log __tests__\dum

my.test.js:13
  [Function: onPress]

希望有帮助。

括号问题有用的链接:http: //jamesknelson.com/javascript-return-parenthesis/


推荐阅读