简体   繁体   中英

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 . 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 . How to mock readFromThis() so that a custom implementation can be done.

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:

readFromThisSpy.mockRestore();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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