Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Next.js and React

Mocking an export fails with 'which has only a getter' or 'Cannot redefine property'

Your error

TypeError: Cannot set property getRequest of #<Object> which has only a getter1 more line it can show

Fix it fast

Most common cause, 1 of 2

The test assigns a mock to an export that is a getter

Drop the assignment and mock the module with jest.mock and a factory. jest.requireActual keeps every other export real, and only the function you name becomes a mock.

Fix
import { getRequest } from '../api';
import { loadUser } from './loadUser';

jest.mock('../api', () => ({
  __esModule: true,
  ...jest.requireActual('../api'),
  getRequest: jest.fn(),
}));

test('loads the user', async () => {
  jest.mocked(getRequest).mockResolvedValue({ id: 1 });
  await loadUser(1);
  expect(getRequest).toHaveBeenCalledWith('/users/1');
});
Did this fix it?
Full steps for this cause: check, fix, verify

Short answer

TypeError: Cannot set property getRequest of #<Object> which has only a getter means a test assigned a mock to an export that TypeScript compiled into a getter. Since Jest 26.6.1, jest.spyOn on such an export fails with Cannot redefine property instead. Use jest.mock with a factory, or spy on the defining file. Applies to Jest 30.

  • Applies to Jest 30.5, ts-jest or tsc CommonJS output, TypeScript 5.x and 6.0, Node.js 22, 24 and 26
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Which cause do you have?

Print the property descriptor of the export your test touches, using the same import the test uses. A get function with configurable: false is a compiled re-export: assigning to it gives the getter message (cause 1) and spying on it gives Cannot redefine property (cause 2). A plain value with writable: true means this export is not the problem.

Run this first
import * as api from '../api';

test('descriptor', () => {
  console.log(Object.getOwnPropertyDescriptor(api, 'getRequest'));
});

Then find the line you see in this list and open its fix:

  1. 1The test assigns a mock to an export that is a getterThe failing line is an assignment such as api.getRequest = jest.fn(), and the message ends in which has only a getter
  2. 2jest.spyOn targets a barrel that re-exports the functionThe test calls jest.spyOn(api, 'getRequest') where api is an index file with export * from or export { getRequest } from, and Jest reports Cannot redefine property: getRequest

What does the error look like?

  • TypeError: Cannot set property getRequest of #<Object> which has only a getter
  • TypeError: Cannot redefine property: getRequest

Cause 1 of 2

The test assigns a mock to an export that is a getter

You seeThe failing line is an assignment such as api.getRequest = jest.fn(), and the message ends in which has only a getter

Check

Cannot set property getRequest of #<Object> which has only a getter is the V8 TypeError for writing to a property that has a getter and no setter; MDN notes it is thrown in strict mode only. Since TypeScript 3.9, CommonJS output uses get accessors to emulate the live bindings of ES modules, and the 3.9 release post says the getters made for export * cannot be overridden with a simple assignment.

Check
grep -rnE "^\s*[A-Za-z_]+\.[A-Za-z_]+\s*=\s*jest\.fn" src/ test/

Fix

Drop the assignment and mock the module with jest.mock and a factory. jest.requireActual keeps every other export real, and only the function you name becomes a mock.

Fix
import { getRequest } from '../api';
import { loadUser } from './loadUser';

jest.mock('../api', () => ({
  __esModule: true,
  ...jest.requireActual('../api'),
  getRequest: jest.fn(),
}));

test('loads the user', async () => {
  jest.mocked(getRequest).mockResolvedValue({ id: 1 });
  await loadUser(1);
  expect(getRequest).toHaveBeenCalledWith('/users/1');
});

Verify

The test file passes and the mock records the call.

Verify
npx jest src/loadUser.test.ts

Confirmed by jestjs.io

Did this fix it?

Cause 2 of 2

jest.spyOn targets a barrel that re-exports the function

You seeThe test calls jest.spyOn(api, 'getRequest') where api is an index file with export * from or export { getRequest } from, and Jest reports Cannot redefine property: getRequest

Check

Current Jest redefines a getter-backed property with Object.defineProperty when you spy on it, a change the changelog for 26.6.1 links to TypeScript 3.9 exports; before that, spying on such an export failed with the getter message. Cannot redefine property means the property is non-configurable, and MDN explains that such a property cannot be defined again, so the spy cannot be installed on the barrel.

Check
grep -nE "export (\*|\{)" src/api/index.ts

Fix

Spy on the module that defines the function instead of on the barrel. First check with the descriptor from the first step that its export is a plain writable property; if it is, the spy installs, and the barrel's live-binding getter passes the spy on to code that imports through the barrel. Otherwise use the jest.mock factory from cause 1.

Fix
// src/api/index.ts contains: export * from './request';
import * as request from '../api/request'; // the defining module
import { loadUser } from './loadUser';      // imports from '../api'

test('loads the user', async () => {
  const spy = jest.spyOn(request, 'getRequest').mockResolvedValue({ id: 1 });
  await loadUser(1);
  expect(spy).toHaveBeenCalled();
  spy.mockRestore();
});

Verify

The spy is created without an error and records the call made through the barrel.

Verify
npx jest src/loadUser.test.ts

Confirmed by raw.githubusercontent.com

Did this fix it?

How do I stop it coming back?

  • Mock at the module boundary with jest.mock factories instead of patching properties of imported objects.
  • In tests, import a function you want to spy on from the file that defines it, never from an index barrel.
  • After a TypeScript or ts-jest upgrade breaks spies, compare property descriptors before rewriting tests; the shape of the compiled exports is what changes.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine on the same stack: TaxiDex, QistLock, Workforce.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.