gpt4 book ai didi

javascript - 如何在 componentDidMount 中模拟类函数

转载 作者:行者123 更新时间:2023-12-03 00:39:30 27 4
gpt4 key购买 nike

class myClass extends React.Component {
async componentDidMount(){
const xyz = helperclass.queryParameters('parameter')
// how can I mock xyz to help me change the value to test the conditional below
if(xyz){
// do something here
}
}
}

已经编辑了上面的代码,现在我想通过模拟它来测试 const xyz 到辅助函数的值,然后返回不同的东西来测试条件中的内容是否已完成

最佳答案

由于myFunctionToMock是原型(prototype)方法,因此可以模拟为

jest.spyOn(MyClass.prototype, 'myFunctionToMock').mockImplementation(...);

在类实例化之前。

Enzyme 中的另一个选项是禁用 disableLifecycleMethods option 的钩子(Hook)。 ,模拟 wrapper.instance() 上的方法并手动调用 componentDidMount

如果一个方法不属于this,则可以在它所属的对象上模拟它:

jest.spyOn( helperclass, 'queryParameters').mockImplementation(...);

同样,这应该在类实例化之前完成,否则需要使用 disableLifecycleMethods

关于javascript - 如何在 componentDidMount 中模拟类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53518787/

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