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"
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.
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' .
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.
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.
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')
You could use Object.defineProperty
Object.defineProperty(myObj, 'prop', { get: jest.fn(() => 'bar'), set: jest.fn() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With