Comments (4)
Inconveniently named restoreAllMocks
is not related to vi.mock
, so it doesn't mention the vi.mock
behaviour in the documentation.
So is there no way to have different mocks for different test / suites?
There are several ways you can achieve it. vi.mock
is called only once, but you can setup a hoisted spy that can be changed in different tests:
import { envSchema, fetchCdkConfig } from './cdk-config.js'
const getFromSsm = vi.hoisted(() => vi.fn())
vi.mock('./config-client.js', () => {
const ConfigClient = vi.fn();
ConfigClient.prototype.getFromSsm = getFromSsm
return { ConfigClient };
})
test('returns a valid envSchema object', () => {
getFromSssm.mockReturnValue(generateMock(envSchema))
const actual = await fetchCdkConfig();
expect(envSchema.safeParse(actual).success).toBe(true);
})
test('breaks if it gets an invalid envSchema object', async () => {
getFromSssm.mockReturnValue({ name: 'home', catchphrase: 'doh' })
const sut = async () => await fetchCdkConfig();
await expect(sut).rejects.toThrow(); // make sure you await it
})
You can also just spy on methods without mocking the module:
import { envSchema, fetchCdkConfig } from './cdk-config.js'
import { ConfigClient } from './config-client.js'
const getFromSsm = vi.fn()
ConfigClient.prototype.getFromSsm = getFromSsm
// same code for tests
If you really want to mock several times, there is vi.doMock
API: https://vitest.dev/api/vi.html#vi-domock
but make sure that you import from ./cdk-config.js
inside of every test again as it only mocks the next import:
The next dynamic import of the module will be mocked.
from vitest.
Very helpful, thank you very much for the explanation!
from vitest.
vi.mock
is hoisted, so your code is only actually called once. Please refer to the documentation: https://vitest.dev/api/vi.html#vi-mock
from vitest.
I see. I looked at the documentation for restAllMocks
where nothing of the sort is mentioned
Will call .mockReset() on all spies. This will clear mock history and reset its implementation to an empty function (will return undefined).
So is there no way to have different mocks for different test / suites?
from vitest.
Related Issues (20)
- testNamePattern doesn't parse RegEx'es in the CLI, or documentation is unclear HOT 2
- get error "Could not parse CSS stylesheet" when CSS file contains nested rules HOT 2
- Issue with `vitest --run --changed` when used with lint-staged on Windows HOT 2
- Default reporter emits `prepare` longer than `Duration` when prepare takes longer than 1s HOT 3
- test.each does not print -0 and -NaN correctly
- `vi.fn()` performs an extra _await_ leading to mismatching behaviour when compared with normal function HOT 6
- API for timer mocks that are safely isolated between tests HOT 3
- There's no console.log output from 'beforeAll' and 'afterAll' when running tests via Webstorm / Aqua IDE HOT 1
- Add support for Node.js 20 `--env-file` flag HOT 6
- vitest fails to load typescript worker code in node (but does so correctly in browser mode) HOT 6
- Better output in UI mode for screen.debug() HOT 2
- ReferenceError on globals using Vitest HOT 2
- Additional type definitions are ignored
- Second (Custom Message) Argument Breaks expect().toBeVisible() HOT 2
- Missing link in Documentation mocking requests HOT 1
- vi.stubEnv documentation and typing differ from each other
- `MY_ENV=abc vitest` exposes `import.meta.env.MY_ENV === "abc"` HOT 2
- Support it() as well for bench HOT 2
- Vitest 1.6.0 upgrade breaks sandboxing the filesystem from tests 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 vitest.