在JavaScript中使用笑话模拟类方法

时间:2019-03-03 14:30:31

标签: javascript jestjs

我有一个类,该类在render下调用一个函数,该函数从this中读取一个值。有什么方法可以模拟该功能,以便测试可以成功运行。

Class Car extends PureComponent{
    readFromThis = () => {
        const helper = this.helper;
        return helper.key();
    }
    render() {
        return (<div>{this.readFromThis()}</div>)
    }
};
export { Car };

这里helper未定义,因此helper.key()记录错误,并且测试失败,并显示错误-> cannot read property key of undefined。如何模拟readFromThis(),以便可以执行自定义实现。

1 个答案:

答案 0 :(得分:0)

对于模拟这样的方法,我相信您可以执行以下操作:

const readFromThisSpy = jest.spyOn(Car.prototype, 'readFromThis').mockImplementation(() =>
  {
    // Your mock implementation here
  });

然后您可以通过执行以下操作在afterAll()afterEach()函数中删除该间谍:

readFromThisSpy.mockRestore();