繁体   English   中英

Jest mock - 如何在 ES 模块内的钩子内监视 function 内的 function?

[英]Jest mock - how to spy on a function, within a function, within a hook within an ES module?

我有这个要模拟的模块:

import { createContext, useContext } from 'react'

const SomeContext = createContext({
  set: () => null,
  reset: () => null,
})

export const useSomeContext = () => useContext(SomeContext)

...这是它在自定义反应钩子中的使用方式:

import { useSomeContext } from './someContext'

export const useCustomHook = () => {
  const { reset, set } = useSomeContext()
  useEffect(() => {
    set()
    return reset
  }, [reset, set])
  ...
}

我正在尝试测试在useCustomHook组件呈现时是否调用了 function set 这是我编写这样一个测试的尝试:

import * as useSomeContextModule from '../someContext'
import { useCustomHook } from '../useCustomHook'

const mockReset = jest.fn()
const mockSet = jest.fn()

jest.mock('../someContext', () => {
  const originalModule = jest.requireActual('../someContext')
  return {
    __esModule: true,
    ...originalModule,
    useSomeContext: jest.fn(() => ({
      reset: mockReset,
      set: mockSet,
    })),
  }
})

test('set method is called when useCustomHook renders', () => {
  useCustomHook()
  expect(mockSet).toHaveBeenCalled()
})

但是,我得到这个错误:

TypeError:无法解构“(0,_index.useSomeContext)(...)”的属性“重置”,因为它未定义。

   7 |
   8 | export const useCustomHook = () => {
>  9 |   const { reset, set } = useSomeContext()

而不是使用jest.mock我使用jest.spyOn

import * as useSomeContextModule from '../someContext'
import { useCustomHook } from '../useCustomHook'
import { renderHook, cleanup } from '@testing-library/react-hooks'

const mockReset = jest.fn()
const mockSet = jest.fn()

beforeEach(() => {
    jest.spyOn(useSomeContextModule, 'useSomeContext').mockReturnValue({
      reset: mockReset,
      set: mockSet,
    })
  })

test('set method is called when useCustomHook renders', () => {
  renderHook(() => useCustomHook())
  expect(mockSet).toHaveBeenCalledOnce()
})

test('reset method is called when useCustomHook unmounts', async () => {
  renderHook(() => useCustomHook())
  await cleanup()
  expect(mockReset).toHaveBeenCalledOnce()
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM