I have a function that returns a object
function getSettings() {
return {
foo: 'bar'
}
}
And I have a function that uses the function above internally
function myFunction() {
const { foo } = getSettings()
return foo
}
And I have a test that I want to change the value of foo
it('', async () => {
const value = '123'
const fooObj = {value: '123'}
jest.spyOn(getSettings, 'foo').mockReturnValue(fooObj )
const result = myFunction()
expect(result).toBe(value)
})
But this doesn't work. Any ideia how to mock the return value of getSettings?
You cant do jest.spyOn(getSettings, 'foo') you need to put the object/module in the first argument and the second argument should be the function name.
You can test it by changing it to:
const fileWithGetSetting = require('<your-path>');
it('', async () => {
// the key should be foo and not value
const fooObj = {foo: '123'}
jest.spyOn(fileWithGetSetting, 'getSettings').mockReturnValue(fooObj)
const result = myFunction()
expect(result).toBe(fooObj.foo)
})
If foo is primitive (like in your test), you need to update the object property if the value
function myFunction() {
const settings = getSettings()
// operation on setting.foo (if foo is primitive)
return setting.foo
}
And pass the object in the test and not the primitive value
it('', async () => {
const obj = {foo: '123'}
jest.spyOn(getSettings, 'foo').mockReturnValue(obj)
const result = myFunction()
expect(result).toBe(obj.foo)
})
When you passed foo in your tests you passed it by value, you need to pass it by reference