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.