Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/vitest-dev/vitest. Next generation testing framework powered by Vite. vitest.dev
test testing-tools vite
Something went wrong. Try again.
Markdown
Mocking Globals #
You can mock global variables that are not present with jsdom or node by using vi.stubGlobal helper. It will put the value of the global variable into a globalThis object.
By default, Vitest does not reset these globals, but you can turn on the unstubGlobals option in your config to restore the original values after each test or call vi.unstubAllGlobals() manually.
import { vi } from 'vitest'
const IntersectionObserverMock = vi.fn(class {
disconnect = vi.fn()
observe = vi.fn()
takeRecords = vi.fn()
unobserve = vi.fn()
})
vi.stubGlobal('IntersectionObserver', IntersectionObserverMock)
// now you can access it as `IntersectionObserver` or `window.IntersectionObserver`