简体   繁体   English

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

[英]Mocking class method using jest in javascript

I have a class in which under render it calls a function that reads a value from this . 我有一个类,其中在render下它调用一个函数,该函数从this读取一个值。 Is there any way to mock that function so that test can run successfully. 有什么方法可以模拟该功能,以便测试可以成功运行。

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

Here helper is undefined so helper.key() logs error and test fails to run with error --> cannot read property key of undefined . 这里的helper未定义,因此helper.key()记录错误,并且测试无法运行,并显示错误-> cannot read property key of undefined How to mock readFromThis() so that a custom implementation can be done. 如何模拟readFromThis()以便可以执行自定义实现。

For mocking a method like this, I believe you can do the following: 对于模拟这样的方法,我相信您可以执行以下操作:

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

And then you can tear down that spy in the afterAll() or afterEach() function by doing the following: 然后,您可以通过执行以下操作在afterAll()afterEach()函数中afterAll()该间谍:

readFromThisSpy.mockRestore();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM