【问题标题】:How to test 'didFocus' from react navigation with jest如何用玩笑从反应导航中测试“didFocus”
【发布时间】:2019-11-20 09:12:02
【问题描述】:

我有一个看起来像这样的组件

async componentDidMount() {
    const { navigation } = this.props
    this.subs = [
      navigation.addListener('didFocus', () => this.onComponentFocus()),
    ]
  }

  onComponentFocus() {
    const { dispatch } = this.props
    dispatch(fetchDevices())
  }

现在我想编写一个测试 chekcs fetchDevice 被调用一次。第一个想法是像这样模拟 Navigation

常量导航 = { 导航:jest.fn(), }

但是现在我该如何检查 this.subs 以及如何检查 fetchDevices 被解雇了?

【问题讨论】:

  • 这取决于fetchDevices() 来自哪里

标签: react-native jestjs react-navigation


【解决方案1】:

如果我们假设fetchDevices 来自图书馆

Component.spec.js
import fetchDevices from 'device-fetcher';
jest.mock('device-fetcher');

// as your component accepts the dispatch function
// you can create it as mock function
const mockDispatch = jest.fn();

// since in your implementation you're calling navigation.addListener
const mockNavigation = {
  navigate: jest.fn(),
  // it should also have 
  addListener: jest.fn()
};

describe('Component', () => {

  const wrapper = shallow(<Component navigation={mockNavigation} dispatch={mockDispatch} />);

  describe('navigation didFocus', () => {
    beforeAll(() => {
      // get .addEventListener calls with 'didFocus'
      mockNavigation.addEventListener.mock.calls
        .filter(([eventName]) => eventName === 'didFocus')
        // iterate over the "attached" handlers
        .map(([eventName, eventHandler]) => {
          // and trigger them
          eventHandler();
        });
    });

    it('should have called the dispatch with the result of fetchDevices', () => {
      expect(mockDispatch).toHaveBeenCalledWith(
        fetchDevices.mock.results[0].value
      );
    });
  });
});

注意:它没有经过测试,只是一个解决方案大纲


编辑:如果fetchDevices 是一个属性而不是模拟你定义模拟函数的库

const fetchDevices = jest.fn();

// and pass it to the component
shallow(<Component navigation={mockNavigation} dispatch={mockDispatch} fetchDevices={fetchDevices} />);

然后你应该对它有相同的断言

【讨论】:

  • 嗨对不起 testDevices 是一个动作。我要测试的是测试设备在应用程序打开时运行。外部库是将 onComponentFocus 挂钩到 componentDidMount
猜你喜欢
  • 2021-10-08
  • 1970-01-01
  • 2017-01-25
  • 2019-08-08
  • 2020-03-02
  • 2020-06-15
  • 1970-01-01
  • 2015-10-27
  • 2021-02-26
相关资源
最近更新 更多