Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix TypeError: jest.replaceProperty is not a function when mocking a const

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?

like image 254
Avtar Avatar asked Oct 20 '25 01:10

Avtar


1 Answers

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';
like image 153
skizzle Avatar answered Oct 21 '25 14:10

skizzle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!