TypeScript构建Express服务器时Jest模拟类方法遇TS2339错误求助
Let’s break down why you’re hitting the TS2339 error and walk through actionable fixes:
The Root Cause
TypeScript enforces type checking based on the original Orig class definition in src/orig.ts—it has no awareness of the __fake static property you added in your mock file. When you try to access Orig.__fake, TypeScript throws TS2339 because that property doesn’t exist in the original type schema.
Solution 1: Augment the Original Class Type
You can extend the type of the Orig class to include the __fake property using TypeScript’s module augmentation. This tells TypeScript to recognize the mock-only property as valid:
- Create a type declaration file (e.g.,
src/orig.mock.d.ts) to augment the original module:
// src/orig.mock.d.ts import { Orig } from './orig'; declare module './orig' { interface Orig { /** Static fake property for Jest mocking */ __fake: string; } }
- Ensure your
tsconfig.jsonincludes this declaration file. Most standard configs automatically pick up.d.tsfiles in the source directory, but you can explicitly add it to theincludearray if needed.
Solution 2: Use Type Assertion in Tests
If you only need to access __fake in test files, a quick fix is to use type assertion to bypass TypeScript’s strict checking for the mock property:
// In your test file import { Orig } from '../src/orig'; jest.mock('../src/orig'); // Assert that Orig includes the __fake property const mockedOrig = Orig as typeof Orig & { __fake: string }; // Now you can modify or access __fake without TS errors mockedOrig.__fake = 'custom fake value'; expect(mockedOrig.testFunc()).toBe('custom fake value');
Solution 3: Avoid Extra Properties with Jest Mock Functions
Instead of adding a custom __fake property, use Jest’s built-in mock functions to control return values. This eliminates type mismatches entirely:
Update your mock file to use a Jest mock function:
// src/__mocks__/orig.ts export class Orig { static testFunc = jest.fn(() => 'fake'); }
Then in your tests, adjust the mock return value like this:
// In your test file import { Orig } from '../src/orig'; jest.mock('../src/orig'); // Type assertion to access the mock function's methods const mockedTestFunc = Orig.testFunc as jest.Mock; mockedTestFunc.mockReturnValue('custom fake'); expect(Orig.testFunc()).toBe('custom fake');
Quick Check: Verify Jest Mock Resolution
Ensure your jest.config.js (or jest.config.ts) is set to recognize mocks in the __mocks__ directory—standard setups handle this automatically, but if you’re using custom import paths, confirm the mock path aligns with the original module’s import path.
内容的提问来源于stack exchange,提问作者Tomer Amir

