简体   繁体   English

监视从 3rd 方库钩子返回的函数

[英]Spy on function returned from 3rd party library hook

I am not able to figure out hot to spy on navigate function returned by useNavigation hook from React navigation v5.我无法弄清楚React 导航v5 中useNavigation钩子返回的navigate函数的useNavigation

I have a simple Link component:我有一个简单的Link组件:

const Link = props => {
  const { to, children, ...restProps } = props;
  const navigation = useNavigation();

  const handlePress = useCallback(() => navigation.navigate(to), [navigation, to]);

  return (
    <TouchableOpacity testID="link" onPress={handlePress}>
      <Text
        {...restProps}
      >
        {children}
      </Text>
    </TouchableOpacity>
  );
};

and coresponding test:和相应的测试:

jest.mock('@react-navigation/native', () => ({
  ...jest.requireActual('@react-navigation/native'),
  useNavigation: () => ({
    navigate: jest.fn(() => 'mocked navigate'),
  }),
}));

import { useNavigation } from '@react-navigation/native';

const spy = jest.spyOn(useNavigation, 'navigate');

describe('<Link />', () => {
  it('navigates', () => {
    const link = render(<Link to="TestScreen">Test link</Link>);
    fireEvent.press(link.getByTestId('link'));

    expect(spy).toBeCalledTimes(1);
  })
});

Of course this won't work, because in const spy = jest.spyOn(useNavigation, 'navigate');当然这行不通,因为在const spy = jest.spyOn(useNavigation, 'navigate'); navigate isn't function of useNavigation . navigate不是useNavigation功能。 But I tried countless other possibilities and I just cannot figure out how to do it.但是我尝试了无数其他的可能性,我就是不知道该怎么做。

Basically what I am trying to do is to verify that when the link is pressed, it calls expected function with expected parameter and I want the function to be mocked out.基本上我想要做的是验证当链接被按下时,它会调用带有预期参数的预期函数,并且我希望该函数被模拟出来。

I know I'm late, but I had the same issue and wanted to know when did the navigate function was called.我知道我迟到了,但我遇到了同样的问题,想知道导航功能是什么时候调用的。

For it, I mocked the function this way, so the mockedNavigate would be a jest function that I could use later:为此,我以这种方式mockedNavigate了该函数,因此mockedNavigate将是一个我可以稍后使用的玩笑函数:

const mockedNavigate = jest.fn();

jest.mock('@react-navigation/native', () => {
  return {
    ...jest.requireActual('@react-navigation/native'),
    useNavigation: () => ({
      navigate: mockedNavigate,
    }),
  };
});

This allowed me to use this later, and in this case you will not need to spy anymore, this should do the trick:这允许我稍后使用它,在这种情况下,您将不再需要监视,这应该可以解决问题:

expect(mockedNavigate).toHaveBeenCalledTimes(1);

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

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