Categories
JavaScript Answers

How to mock or replace getter function of object with Jest and JavaScript?

Spread the love

Sometimes, we want to mock or replace getter function of object with Jest and JavaScript.

In this article, we’ll look at how to mock or replace getter function of object with Jest and JavaScript.

How to mock or replace getter function of object with Jest and JavaScript?

To mock or replace getter function of object with Jest and JavaScript, we can call the spyOn method.

For instance, we write

class MyClass {
  get something() {
    return "foo";
  }
}

jest.spyOn(MyClass, "something", "get").mockReturnValue("bar");
const something = new MyClass().something;


to call jest.spyOn with MyClass, "something", and 'get' to mock the something getter in MyClass.

We call mockReturnValue to return 'bar' as the value of something.

Then we check if something is 'bar' with

expect(something).toEqual("bar");

Conclusion

To mock or replace getter function of object with Jest and JavaScript, we can call the spyOn method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *