Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock/replace getter function of object with Jest?

In Sinon I can do the following:

var myObj = {     prop: 'foo' };  sinon.stub(myObj, 'prop').get(function getterFn() {     return 'bar'; });  myObj.prop; // 'bar' 

But how can I do the same with Jest? I can't just overwrite the function with something like jest.fn(), because it won't replace the getter

"can't set the value of get"

like image 713
I_like_foxes Avatar asked Apr 29 '17 15:04

I_like_foxes


People also ask

How do you get a mock getter in jest?

If you truly want to mock the getter aspect of your dependency, you can provide a mock getter using Object. defineProperty . For example, if you want to mock a property “isLoading” on your object that has a getter behind it, you could do the following: Object.

Can you mock an object in jest?

The jest object is automatically in scope within every test file. The methods in the jest object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via import {jest} from '@jest/globals' .

How do you mock a real function in jest?

There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a manual mock to override a module dependency.

Does jest spyOn mock?

Before every function is run in the file, jest will mock , and after every , jest will restore the function to its original implementation. Using the hooks for setup ensures that every test is fresh and independent of each other.


Video Answer


2 Answers

For anyone else stumbling across this answer, Jest 22.1.0 introduced the ability to spy on getter and setter methods.

Edit: like in scieslak's answer below, because you can spy on getter and setter methods, you can use Jest mocks with them, just like with any other function:

class MyClass {   get something() {     return 'foo'   } }  jest.spyOn(MyClass, 'something', 'get').mockReturnValue('bar') const something = new MyClass().something  expect(something).toEqual('bar') 
like image 109
Franey Avatar answered Sep 21 '22 03:09

Franey


You could use Object.defineProperty

Object.defineProperty(myObj, 'prop', {   get: jest.fn(() => 'bar'),   set: jest.fn() }); 
like image 28
Alex Robertson Avatar answered Sep 22 '22 03:09

Alex Robertson