We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fs
When trying to mock fs (or node:fs), I'm only able to mock the return value or mock implementation under certain conditions.
node:fs
In the below reproduction, switching the order of the two tests actually makes the tests work.
Note that this project is set to ESM, via "type": "module" in package.json.
"type": "module"
package.json
File:
import { readFileSync } from 'node:fs'; export const readFile = () => { try { return readFileSync('some-file', 'utf-8'); } catch (e) { return ''; } };
Test:
import { readFileSync } from 'node:fs'; import { afterEach, describe, expect, it, vi } from 'vitest'; vi.mock('node:fs', () => ({ readFileSync: vi.fn().mockImplementation(() => ''), })); const mockReadFileSync = vi.mocked(readFileSync); describe('env', () => { afterEach(() => { vi.resetModules(); }); it('should handle a missing file', async () => { mockReadFileSync.mockImplementation(() => { throw new Error('Some error'); }); const { readFile } = await import('./repro'); expect(readFile()).toBe(''); }); it('should read a file', async () => { mockReadFileSync.mockImplementation(() => 'Some contents'); const { readFile } = await import('./repro'); expect(readFile()).toBe('Some contents'); }); });
Config:
import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { mockReset: true, }, });
System: OS: macOS 12.4 CPU: (8) arm64 Apple M1 Memory: 177.42 MB / 16.00 GB Shell: 5.8.1 - /bin/zsh Binaries: Node: 18.6.0 - ~/Library/Caches/fnm_multishells/11869_1657854968244/bin/node npm: 8.13.2 - ~/Library/Caches/fnm_multishells/11869_1657854968244/bin/npm Browsers: Chrome: 103.0.5060.114 Edge: 103.0.1264.62 Firefox: 102.0.1 Safari: 15.5 npmPackages: vitest: ^0.18.0 => 0.18.0
pnpm
The text was updated successfully, but these errors were encountered:
vi.resetModules removes mocks. This is bug with resetModules, and not with ESM mocking. Importing fs has nothing to do with ESM.
vi.resetModules
resetModules
Sorry, something went wrong.
Thank you!
Successfully merging a pull request may close this issue.
Describe the bug
When trying to mock
fs
(ornode:fs
), I'm only able to mock the return value or mock implementation under certain conditions.In the below reproduction, switching the order of the two tests actually makes the tests work.
Note that this project is set to ESM, via
"type": "module"
inpackage.json
.Reproduction
File:
Test:
Config:
System Info
Used Package Manager
pnpm
Validations
The text was updated successfully, but these errors were encountered: