react-native - 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())
})
解决方案
你的代码有一些错误,首先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/
推荐阅读
- view - 如何为每个设备创建另一个独特的视图?
- javascript - 错误 403 AJAX 请求 JavaScript(instagram 直接消息)
- python - 如何修复“break”命令在 python 中使用键盘和时间输入不起作用?
- raylib - Makefile:2: *** 缺少分隔符。停止。我该如何解决这个问题我是 Raylib for C++ 的新手
- wufoo - 剥离开放价值订阅或产品价值
- javascript - JavaScript 中的简单 MSAL 登录/身份验证
- python - 我刮掉了帖子的评论,但他们没有刮掉
- python - 从打印/输出管理器和版本信息中停止 Selenium ChromeWebdriver?
- linux - 无法在 Linux 中增加打开文件限制
- android - 匕首刀柄:注释类@Singleton 和提供函数@Singleton 之间的区别