我正在使用 Enzyme 和 Jest 为我的 React App 前端编写单元测试。当我尝试渲染登录屏幕时,它无法看到我在尝试 mount() 渲染时传递的一些 Prop 。浅层渲染工作正常,我可以测试我的 componentDidMount 和 componentWillReceiveProps 方法。
我尝试了多种渲染方式。将 mount() 与 Provider 一起使用,硬编码传入 props。似乎没有任何效果。
下面是一个工作测试和一个损坏的测试。第一个工作正常,但安装测试被破坏:
我正在传递这些 Prop :
let props = {
actions: mockProps.actions,
auth: {
isAuthenticated: false,
isFetching: false
},
history: mockProps.history,
location: {
pathname: "/login",
search: "",
hash: "",
key: "0m32x8"
},
match: mockProps.match
}
mockProps 是一个 json 文件,其中包含来自 chrome 中的 React Dev Tool 的示例 props。
// Working Shallow Rendered Test
it('componentWillReceiveProps', () => {
const componentWillReceivePropsSpy = jest.spyOn(Login.prototype, 'componentWillReceiveProps')
shallowWrapper.setProps({ location: { search: "testing" } })
expect(componentWillReceivePropsSpy).toHaveBeenCalled()
})
// Broken Mount Rendered Test
it('Mount Test', () => {
mount(<Provider store={store}><Login {...props}/></Provider>)
})
当组件尝试在此处设置初始状态时会发生错误:
state = {
shouldRedirect: false,
errorShown: false,
fields: {
username: '',
password: ''
},
token: q.parse(this.props.location.search).token,
fieldErrors: {}
};
找不到this.props.location.search
。
最佳答案
在使用高阶组件时,最好也导出基本组件(在包装它之前),这样我们就可以在没有包装器的情况下进行测试,并简单地传递所需提供程序的模拟。
我也遇到了同样的问题,这就是我解决的方法!
关于javascript - 为什么在安装渲染时我的 Prop 没有传递到我的组件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852855/