Categories
JavaScript Answers

How to spyOn a value property rather than a method with Jasmine and JavaScript?

Spread the love

Sometimes, we want to spyOn a value property rather than a method with Jasmine and JavaScript.

In this article, we’ll look at how to spyOn a value property rather than a method with Jasmine and JavaScript.

How to spyOn a value property rather than a method with Jasmine and JavaScript?

To spyOn a value property rather than a method with Jasmine and JavaScript, we can spy on the getter of the property.

For instance, we write

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); 
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); 
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); 

in our test.

We call spyOnProperty with the arguments that leads to the myObj.myGetterNsme getter.

Then we call and.returnValue to mock the return value of the getter.

We call callThrough to call the getter.

Conclusion

To spyOn a value property rather than a method with Jasmine and JavaScript, we can spy on the getter of the property.

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 *