Skip to content

How to use different mocks for each test with vi.mock? #3589

Closed Answered by sheremet-va
marcadrian-it asked this question in Q&A
Discussion options

You must be logged in to vote

You can pass down variables with vi.hoisted and change the implementation before running a test:

import { namedExport } from './path/to/module.js'

const mocks = vi.hoisted(() => {
  return {
    namedExport: vi.fn(),
  }
})

vi.mock('./path/to/module.js', () => {
  return {
    namedExport: mocks.namedExport,
  }
})

it('test 1', () => {
	mocks.namedExports.mockReturned(true)
	// some test
})

it('test 2', () => {
	mocks.namedExports.mockReturned(false)
	// some test
})

Replies: 2 comments 8 replies

Comment options

You must be logged in to vote
7 replies
@marcadrian-it
Comment options

@sheremet-va
Comment options

Answer selected by marcadrian-it
@sinaza
Comment options

@tnt-glenn-mccomb
Comment options

@Sti2nd
Comment options

@abdelrahman543873
Comment options

Comment options

You must be logged in to vote
1 reply
@sheremet-va
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
8 participants