-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Provide disposable APIs for releasing mocks #8425
Copy link
Copy link
Labels
p2-nice-to-haveNot breaking anything but nice to have (priority)Not breaking anything but nice to have (priority)pr welcome
Description
Clear and concise description of the problem
It's easy to forget to release mocks. For example, the following code mocking the node:path module pollutes subsequent test cases by forgetting to release the mock.
import { describe, expect, vi, it } from 'vitest';
describe('pollution', () => {
it('mocks a module', async () => {
vi.doMock(import('node:path'), async (importActual) => {
const pathActual = await importActual();
return {
...pathActual,
default: 'mocked!'
}
})
const path = await import('node:path');
expect(path.default).toBe('mocked!');
})
it('should not be mocked anymore', async () => {
const path = await import('node:path');
expect(path.default).not.toBe('mocked!'); // fails; polluted by other test case
});
})Suggested solution
It would be highly ergonomic to release mocks by providing a disposable API that releases the mock
import { describe, expect, vi, it } from 'vitest';
describe('no pollution', () => {
it('mocks a module', async () => {
using _temporary_mock = vi.disposableMock(import('node:path'), async (importActual) => {
const pathActual = await importActual();
return {
...pathActual,
default: 'mocked!'
}
})
const path = await import('node:path');
expect(path.default).toBe('mocked!');
})
it('should not be mocked anymore', async () => {
const path = await import('node:path');
expect(path.default).not.toBe('mocked!');
});
})Alternative
One can either
- keep track of all mocked modules, and use a
beforeEach/afterEachwithvi.doUnmock('node:path'); - use
try ... finallyto callvi.doUnmock('node:path')after callingvi.doMock('node:path');
These both rely on non-local code to clean up the mock state, whereas using would localize all information to the declaration of the mock
Additional context
using is available out of the box in current versions of node.
keywords: explicit resource management
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
p2-nice-to-haveNot breaking anything but nice to have (priority)Not breaking anything but nice to have (priority)pr welcome
Type
Projects
Status
Approved