【问题标题】:React Native Enzyme Jest props.onPress is not a functionReact Native Enzyme Jest props.onPress 不是函数
【发布时间】:2018-06-20 23:12:46
【问题描述】:

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

props.onPress() 不是函数

我假设我需要在测试中手动将道具传递给 on press。但我觉得这可能会破坏测试代码结构中现有内容的目的。

家长

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-native jestjs enzyme


    【解决方案1】:

    你的代码有一些错误,首先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/

    【讨论】:

      猜你喜欢
      • 2019-12-09
      • 1970-01-01
      • 2019-09-26
      • 2017-06-25
      • 2019-10-16
      • 2017-07-16
      • 1970-01-01
      • 2018-12-16
      • 2020-12-13
      相关资源
      最近更新 更多