I have a file of const
values, and I want to mock one of those properties to change its value.
const constsMock = jest.mock('./consts', jest.fn().mockReturnValue({ myConst: true }));
jest.spyOn(constsMock, 'myConst');
I tried the above and got the following error:
Cannot spy on the myConst property because it is not a function; undefined given instead. If you are trying to mock a property, use
jest.replaceProperty(object, 'myConst', value)
instead.
Makes sense. So I tried:
import * as consts from './consts'
jest.replaceProperty( consts, 'myConst', true )
Which resulted in:
TypeError: jest.replaceProperty is not a function
So I tried this:
import { replaceProperty } from 'jest'
...which results in a TypeScript warning:
Module '"jest"' has no exported member 'replaceProperty'.ts(2305)
I don't understand why because the replaceProperty()
function is documented in the Jest docs.
Can someone help me use this function correctly to mock a const value?
for anyone stumbling on that: https://jestjs.io/docs/jest-object
seems like the replaceProperty
function is only available, when jest is explicitly imported
// https://jestjs.io/docs/jest-object
INFO
The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from '@jest/globals';
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