我有一个包含2个输入文本字段的组件。
在componentDidMount()
方法中,我呼叫this.refs.password.focus();
我的componentDidMount
内部存在一些棘手的业务逻辑,但在componentDidMount
进行浅层单元测试时,我收到错误
无法访问未定义的密码
我检查了浅组件的实例,发现this.refs
未定义 。
我的问题是我们如何通过测试来设置它?
Shallow有一个第二个参数,我们可以传递这个参数作为上下文,我们可以设置单元测试的上下文,但似乎什么也没做。
对此区域的任何帮助都将受到高度赞赏。
答案 0 :(得分:8)
解决此问题的最简单方法是通过实例设置refs
。
const component = shallow(<Component />)
const instance = component.instance()
instance.refs = {
password: {
getRenderedComponent: jest.fn(() => ({
focus: jest.fn
}))
}
}
答案 1 :(得分:4)
shallow
没有ref
方法。您需要使用mount
来完整地测试渲染。
参考文献: API文档: https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md