简体   繁体   English

模拟返回函数的模块并测试该函数是否被调用

[英]Mock a module that returns a function and test that this function was called

I want to test a React component that, internally, uses a custom hook (Jest used).我想测试一个 React 组件,该组件在内部使用自定义钩子(Jest used)。 I successfully mock this hook but I can't find a way to test the calls on the functions that this hook returns.我成功地模拟了这个钩子,但我找不到一种方法来测试这个钩子返回的函数的调用。

Mocked hook被嘲笑的钩子

const useAutocomplete = () => {
  return {
    setQuery: () => {}
  }
}

React component反应组件

import useAutocomplete from "@/hooks/useAutocomplete";

const MyComponent = () => {
  const { setQuery } = useAutocomplete();

  useEffect(() => {
    setQuery({});
  }, [])
  ...
}

Test测试

jest.mock("@/hooks/useAutocomplete");

it("sets the query with an empty object", () => {
  render(<MyComponent />);

  // I want to check the calls to setQuery here
  // e.g. mockedSetQuery.mock.calls
});

CURRENT SOLUTION当前解决方案

I currently made the useAutocomplete hook an external dependency:我目前使 useAutocomplete 挂钩成为外部依赖项:

import useAutocomplete from "@/hooks/useAutocomplete";

const MyComponent = ({ autocompleteHook }) => {
  const { setQuery } = autocompleteHook();

  useEffect(() => {
    setQuery({});
  }, [])
  ...
}

MyConsole.defaultProps = {
 autocompleteHook: useAutocomplete
}

And then I test like this:然后我像这样测试:

const mockedSetQuery = jest.fn(() => {});

const useAutocomplete = () => ({
  setQuery: mockedSetQuery,
});

it("Has access to mockedSetQuery", () => {
  render(<MyComponent autocompleteHook={useAutocomplete} />);

  // Do something

  expect(mockedSetQuery.mock.calls.length).toBe(1);  
})

You can mock the useAutocomplete 's setQuery method to validate if it's invoked.您可以模拟useAutocompletesetQuery方法来验证它是否被调用。

jest.mock("@/hooks/useAutocomplete");

it("sets the query with an empty object", () => {
  const useAutocompleteMock = jest.requireMock("@/hooks/useAutocomplete");
  const setQueryMock = jest.fn();
  useAutocompleteMock.setQuery = setQueryMock;
  render(<MyComponent />);

  // The mock function is called twice
  expect(setQueryMock.mock.calls.length).toBe(1);

});

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

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