【问题标题】:Using react-hooks-testing-library with jest.spyOn - spy is not called将 react-hooks-testing-library 与 jest.spyOn 一起使用 - 不会调用 spy
【发布时间】:2019-06-05 14:31:35
【问题描述】:

我在设置单元测试以确定使用正确参数调用函数时遇到问题。 useAHook 返回函数 foo,它调用函数 bar。代码是这样的

//myModule.js
export const useAHook = (arg1, arg2) => {
  const foo = useCallback(() => {
    bar(arg1, arg2);
  }, [arg1, arg2]);

  return foo;
}

export const bar = (a, b) => {
   //does some stuff with a and b
}

我正在尝试使用renderHookjest.spyOn 对该代码进行单元测试。我想确认调用函数foo 导致bar 被正确的参数调用。我的单元测试是这样的

//myModule.spec.js

import * as myModule from './myModule.js'

it('should call foo with correct arguments', () => {
  const spy = jest.spyOn(myModule, 'bar');
  const { result } = renderHook(() => myModule.useAHook('blah', 1234));
  const useAHookFunc = result.current;

  useAHookFunc();

  // fails, spy is not called
  expect(spy).toBeCalledWith('blah', 1234);
});

结果是测试失败,表明从未调用过spy。我在这里做错了什么还是错误地使用了任何一个工具?

【问题讨论】:

  • 这间接解决了我有一段时间的一个问题。谢谢!

标签: jestjs react-hooks-testing-library


【解决方案1】:

这一行:

import * as myModule from './myModule.js'

...将myModule.js 的模块绑定导入myModule

然后这一行:

const spy = jest.spyOn(myModule, 'bar');

...将bar模块导出包装在一个间谍...

...但是间谍永远不会被调用,因为useAHook 不会为bar 调用模块导出,它只是直接调用bar


如果您修改useAHook 以调用bar 的模块导出,则将调用间谍。

有几种方法可以做到这一点。

您可以将bar 移动到它自己的模块中...

...或者您可以导入myModule.js 的模块绑定,这样您就可以调用bar 的模块导出:

import { useCallback } from 'react';

import * as myModule from './myModule';  // <= import the module bindings

export const useAHook = (arg1, arg2) => {
  const foo = useCallback(() => {
    myModule.bar(arg1, arg2);  // <= call the module export for bar
  }, [arg1, arg2]);

  return foo;
}

export const bar = (a, b) => {
   //does some stuff with a and b
}

【讨论】:

    【解决方案2】:

    我设法窥探了钩子导出方法(使用import * as),然后在实现中注入了一个模拟函数:

    import * as useThingHook from 'useThing'
    
    it('a test', () => {
      const methodMock = jest.fn()
      jest.spyOn(useThingHook, 'usething').mockImplementation(() => ({
        method: methodMock
      }))
    
      act()
    
      expect(methodMock).toHaveBeenCalled()
    })
    

    【讨论】:

      猜你喜欢
      • 2019-02-01
      • 2020-12-01
      • 2019-10-30
      • 2021-06-16
      • 1970-01-01
      • 2023-03-13
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多