在javascript中使用jest模拟类方法
我有一个类,在该类中,它在render下调用一个函数,该函数从在javascript中使用jest模拟类方法,javascript,jestjs,Javascript,Jestjs,我有一个类,在该类中,它在render下调用一个函数,该函数从this读取一个值。是否有任何方法来模拟该函数,以便测试能够成功运行 Class Car extends PureComponent{ readFromThis = () => { const helper = this.helper; return helper.key(); } render() { return (<div>{this.re
this
读取一个值。是否有任何方法来模拟该函数,以便测试能够成功运行
Class Car extends PureComponent{
readFromThis = () => {
const helper = this.helper;
return helper.key();
}
render() {
return (<div>{this.readFromThis()}</div>)
}
};
export { Car };
Class-Car扩展了PureComponent{
readFromThis=()=>{
const helper=this.helper;
返回helper.key();
}
render(){
返回({this.readFromThis()})
}
};
出口{Car};
此处的
helper
未定义,因此helper.key()记录错误,测试无法运行,出现错误-->无法读取未定义的的属性键。如何模拟readFromThis()
,以便进行自定义实现。要模拟这样的方法,我相信您可以执行以下操作:
const readFromThisSpy = jest.spyOn(Car.prototype, 'readFromThis').mockImplementation(() =>
{
// Your mock implementation here
});
readFromThisSpy.mockRestore();
然后,您可以通过执行以下操作,在afterAll()
或afterEach()
函数中拆除该间谍:
const readFromThisSpy = jest.spyOn(Car.prototype, 'readFromThis').mockImplementation(() =>
{
// Your mock implementation here
});
readFromThisSpy.mockRestore();
要模拟这样的方法,我相信您可以执行以下操作:
const readFromThisSpy = jest.spyOn(Car.prototype, 'readFromThis').mockImplementation(() =>
{
// Your mock implementation here
});
readFromThisSpy.mockRestore();
然后,您可以通过执行以下操作,在afterAll()
或afterEach()
函数中拆除该间谍:
const readFromThisSpy = jest.spyOn(Car.prototype, 'readFromThis').mockImplementation(() =>
{
// Your mock implementation here
});
readFromThisSpy.mockRestore();
无法监视readFromThis属性,因为它不是函数;相反,未定义的给定
无法监视readFromThis属性,因为它不是函数;而不是给定未定义的