Comments (6)
As you see CJS has jest.requireActual()
, but it can’t work in ESM. Similar async method for imports is needed as mentioned in the meta issue: #9430
from jest.
require()
does not work in ESM as well as requireActual()
. It might make sense to mention that partial mocking is not yet supported, but that is mentioned in #9430 and the ECMAScript Modules page already links to this issue. In a way several features are not yet working. Not sure if it worth mentioning them in documentation.
As a side note. Jest and Vitest have very different approach to ESM. In Jest a plain JavaScript ESM is simply executed, in Vitest you will see transform time being reported. I don’t know what is that transformation about, but that is: 1. waste of time; 2. not ESM as implemented by Node.js (for instance require
global gets injected).
from jest.
This works:
import { jest } from '@jest/globals';
jest.unstable_mockModule('../foo-bar-baz', () => {
return {
bar: () => 'mocked bar',
};
});
const { bar } = await import('../foo-bar-baz');
test('should do a partial mock', () => {
expect(bar()).toBe('mocked bar');
});
Docs for unstable_mockModule
are available here: https://jestjs.io/docs/ecmascript-modules#module-mocking-in-esm
Trying to make the implementation exactly the same as in the original example, I think this is the correct code:
import { jest } from '@jest/globals';
jest.unstable_mockModule('../foo-bar-baz', async () => {
const originalModule = await import('../foo-bar-baz');
return {
...originalModule,
default: jest.fn(() => 'mocked baz'),
foo: 'mocked foo',
};
});
const { default: defaultExport, bar, foo } = await import('../foo-bar-baz');
test('should do a partial mock', () => {
const defaultExportResult = defaultExport();
expect(defaultExportResult).toBe('mocked baz');
expect(defaultExport).toHaveBeenCalled();
expect(foo).toBe('mocked foo');
expect(bar()).toBe('bar');
});
However, the test never finishes. Seems this issue was reported a while ago: #13851
from jest.
It seems that #10025 is tracking a potential fix for this issue (since 2020)
Since requireActual()
does not work with partial ES6 module mocks, probably the documentation should say this.
Should I make a PR?
from jest.
Similar code works in Vitest using a special method called importOriginal()
: https://stackblitz.com/edit/vitejs-vite-fcr3z9
Vitest supports partial mocks but has a caveat that's well explained in the docs:
It is not possible to mock the foo method from the outside because it is referenced directly. So this code will have no effect on the foo call inside foobar (but it will affect the foo call in other modules):
And then goes on to write:
This is the intended behaviour. It is usually a sign of bad code when mocking is involved in such a manner.
https://vitest.dev/guide/mocking.html#mocking-pitfalls
Probably partial mocks should be generally avoided.
from jest.
This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.
from jest.
Related Issues (20)
- [Bug]: transform esm module in jest-runtime
- No tests found on Windows if any folder in path starts with special character HOT 3
- [Bug]: Unable to run multiple tests through -t argument HOT 4
- [Bug]: `constructorA.mock.instances` not correct when using `jest.fn().mockImplementation(() => ({ ... }))`
- Jest needs disclaimers.
- Document release process
- [Bug]: Jest fails to serialize custom elements with anonymous constructors
- [Bug]: Critical security finding in jest-reporters
- [Bug]: Incorrect Error Stacktrace when using Object.freeze(Object.prototype)
- [Bug]: when adding "disctributed" to a testfile name it no longer runs
- [Bug]: global object is not usable in globalTearDown file
- Top-level 'await' expressions not working even if tried a lot of solutions found in StackOverflow HOT 1
- [Feature]: Upgrade jest-environment-jsdom from v22 to v24 to avoid deprecated punycode warning HOT 4
- [Docs]: `react-test-renderer` deprecated HOT 3
- [Feature]: Support Babel v8 HOT 1
- [Bug]: `transform` does not accept `file:` urls
- [Feature]: babel-jest: opting out babel-preset-jest
- [Docs]: Update jest.restoreAllMocks behavior change HOT 1
- [Bug]: @jest/create-cache-key-function does not have correct type definition
- Import, export syntax error from @azure/storage-blob in nx monorepo HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jest.