-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
Closed
Closed
Copy link
Description
Version
27.5.1
Steps to reproduce
package.json
{
"scripts":{
"test": "node --experimental-vm-modules ./node_modules/.bin/jest --bail --colors --coverage --detectOpenHandles --forceExit --verbose",
},
"jest": {
"preset": "ts-jest/presets/default-esm",
"transform": {
".ts": "ts-jest"
},
"testEnvironment": "node",
"moduleFileExtensions": [
"ts",
"js",
"json"
],
"transformIgnorePatterns": [
"<rootDir>/node_modules/"
],
"globals": {
"ts-jest": {
"useESM": true
}
}
}
}
file1.ts
import {foo2} from "./file2";
export const foo1=async ()=>{
return await foo2()
}
file2.ts
export const foo2=async ()=>{
return Promise.resolve({result:"foo2"})
}
help.ts --> Only one function is mocked, and all other functions remain unchanged
import { jest } from '@jest/globals';
export const mockModuleESM = async (
modulePath: string,
funcToReturnValMock: { name: string; value: any }[],_module?:any
) => {
const module: any = await import(modulePath);
jest.unstable_mockModule(modulePath, () => {
const newModule: any = {};
for (const propKey of Object.keys(module)) {
let i = funcToReturnValMock.findIndex(
keyVal => keyVal.name === propKey
);
// newModule[propKey] = i === -1 ? module[propKey] : jest.fn().mockReturnValue(funcToReturnValMock[i].value)
newModule[propKey] =
i === -1
? module[propKey]
: jest.fn().mockImplementation(() => {
console.log(
'Mock function',
funcToReturnValMock[i].name,
funcToReturnValMock[i].value
);
return funcToReturnValMock[i].value;
});
}
return newModule;
});
};
file1.test.ts
import { jest } from '@jest/globals';
import { mockModuleESM } from './help';
describe('Test ', () => {
beforeEach( () => {
jest.resetModules()
jest.restoreAllMocks()
});
test('Test 11111', async () => {
await mockModuleESM(`../src/file2`, [
{
name: 'foo2',
value: {result:"foo2 mock2"}
}
]);
const { foo1 } = await import(
`../src/file1`
);
const r = await foo1()
expect(r).toEqual({result:"foo2 mock2"});
});
test('Test 22222', async () => {
await mockModuleESM(`../src/file2`, [
{
name: 'foo2',
value: {result:"foo2 mock333"}
}
]);
const { foo1 } = await import(
`../src/file1`
);
const r = await foo1()
expect(r).toEqual({result:"foo2 mock333"});
});
});
Expected behavior
All test should be pass
Actual behavior
FAIL test/file1.test.ts
Test
✓ Test 11111 (17 ms)
✕ Test 22222 (4 ms)
● Test › Test 22222
expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 1
Object {
- "result": "foo2 mock333",
+ "result": "foo2 mock2",
}
Additional context
No response
Environment
System:
OS: macOS 12.2.1
CPU: (10) arm64 Apple M1 Pro
Binaries:
Node: 16.14.2 - /usr/local/bin/node
Yarn: 1.22.17 - /usr/local/bin/yarn
npm: 8.5.0 - /usr/local/bin/npm
npmPackages:
jest: ^27.5.1 => 27.5.1