我要测试componentDidUpdate 我尝试传递{... props}而不定义它 然后,componentDidUpdate首先记录一个空对象,然后不需要更新 这会记录两次,并显示道具未定义 如何在不结束循环的情况下测试componentDidUpdate。
我的代码
componentDidUpdate(updateRequired) {
console.log(this.props);
if (this.props.updateRequired === true) {
this.anotherFunc();
} else {
console.log("update not required")
}
}
anotherFunc() {
this.props.callBackFalse();
}
这是我要测试的代码
componentDidUpdate(updateRequired) {
console.log(this.props);
if (this.props.updateRequired === true) {
this.anotherFunc();
} else {
console.log("update not required")
}
}
我尝试过使用setProps进行测试
it('checks if component updates on receiving props', async (done) => {
const callBackFalse= jest.fn();
let prevProps = {
updateRequired : false,
callBackFalse
}
let nextProps = {
updateRequired : true,
callBackFalse
}
const wrapper = shallow(<Feed {...prevProps} />);
await wrapper.setProps(nextProps);
await expect(callBackFalse).toHaveBeenCalledWith(prevProps,nextProps);
done();
})
,然后进入循环 (这是我如何知道它在控制台上反复打印此代码时进入了循环的方式) console.log src / Components / feed / feed.js:12
{ updateRequired: true,
callBackFalse:
{ [Function: mockConstructor]
_isMockFunction: true,
(rest of jest mock functions) } }
编辑: 从浅水变为山水
it('checks if component updates on receiving props', async (done) => {
const callBackFalse = jest.fn();
let prevProps = {
updateRequired: false,
callBackFalse
}
let nextProps = {
updateRequired: true,
callBackFalse
}
const wrapper = mount(<Feed {...prevProps} />);
wrapper.setProps(nextProps);
done();
await wrapper.instance.callBackFalse;
expect(callBackFalse).toHaveBeenCalledTimes(1);
})
现在它可以运行并通过了测试,但仍然继续循环运行,并像这样在控制台上继续打印
console.log src / Components / feed / feed.js:12
{ updateRequired: true,
callBackFalse:
{ [Function: mockConstructor]
_isMockFunction: true,
(rest of jest mock functions)} }
答案 0 :(得分:0)
在您的componentDidUpdate
中,您需要先将prevProps
与当前props
进行比较,然后再进行可能会更改组件当前状态的操作,否则可能会导致无限循环,正如您在文档https://reactjs.org/docs/react-component.html#componentdidupdate中所看到的。
因此您的代码应如下所示:
componentDidUpdate(prevProps) {
if (prevProps.updateRequired !== this.props.updateRequired) {
console.log(this.props);
if (this.props.updateRequired === true) {
this.anotherFunc();
} else {
console.log("update not required")
}
}
}