gpt4 book ai didi

javascript - 如何在不循环结束的情况下测试 componentDidUpdate

转载 作者:行者123 更新时间:2023-11-30 06:12:17 24 4
gpt4 key购买 nike

我想测试 componentDidUpdate我尝试传递 {...props} 而不定义它然后 componentDidUpdate 首先记录一个空对象,然后不需要更新这会记录它们两次并显示 props is not defined如何在不结束循环的情况下测试 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)} }

最佳答案

在您的 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")
}
}
}

关于javascript - 如何在不循环结束的情况下测试 componentDidUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58180062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com