Vitest - 仅在一次测试中模拟组件

问题描述 投票:0回答:1

我想在Parent中模拟一个名为Child的组件。所有测试都应使用原始子组件,但其中一个测试应使用 Mock。我怎样才能做到这一点?

reactjs testing jestjs mocking vitest
1个回答
0
投票

在组件上使用间谍功能也同样有效,并且非常适合仅在一次测试中模拟组件。

我在文档中发现了这一点: https://vitest.dev/guide/mocking.html#cheat-sheet

vi.spyOn 示例:

import * as exports from './some-path.js'

vi.spyOn(exports, 'SomeClass').mockImplementation(() => {
    // whatever suites you from first two examples
})

并尝试像这样模拟组件:

 import * as childComponent from './path/to/child.tsx'

 describe('Parent', () => {
      it('tests with mocked child', () => {
           vi.spyOn(childComponent, 'Child').mockImplementation((props: ChildProps) => {
                return (
                     <div>
                          // your component mock able to use component props as well
                     </div>
                )
      })
 })

其他可能有帮助但没有解决我的具体情况的来源:

对不同的测试使用不同的模拟:

https://github.com/vitest-dev/vitest/discussions/3589#discussioncomment-6195214

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
})

还有这个:https://github.com/vitest-dev/vitest/discussions/4328

© www.soinside.com 2019 - 2024. All rights reserved.