Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中使用jest模拟类方法_Javascript_Jestjs - Fatal编程技术网

在javascript中使用jest模拟类方法

在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

我有一个类,在该类中,它在render下调用一个函数,该函数从
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属性,因为它不是函数;而不是给定未定义的