Skip to content

Mocking Globals

你可以使用 vi.stubGlobal 助手来模拟 jsdomnode 中不存在的全局变量。它会将全局变量的值放入 globalThis 对象中。

默认情况下,Vitest 不会重置这些全局变量,但你可以在配置中开启 unstubGlobals 选项,以便在每次测试后恢复原始值,或者手动调用 vi.unstubAllGlobals()

ts
import { vi } from 'vitest'

const IntersectionObserverMock = vi.fn(() => ({
  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`

Released under the MIT License.