How to test async function with spyOn?

半腔热情 提交于 2021-02-19 02:57:09

问题


I am trying to test an async function in a react native app.

class myClass extends React.Component {

  ...

  closeModal = async () => {

    if (someCondition) {
      await myFunction1();
    } else {
      await myFunction2();
    }

    this.props.navigation.state.params.onGoBack();
    this.props.navigation.navigate('Main');
  };

  ...

}

This is my test:

const navigation = {
  navigate: jest.fn(),
  state: { params: { onGoBack: jest.fn() } },
};

const renderComponent = overrides => {
  props = {
    navigation,
    ...overrides,
  };

  return shallow(< myClass.wrappedComponent {...props} />);
};


describe('When the user presses the close icon', () => {
    it('should close the modal', () => {
      const wrapper = renderComponent();
      const instance = wrapper.instance();
      const spyCloseModal = jest.spyOn(instance, 'closeModal');
      instance().forceUpdate();
      component
        .find({ testID: 'close-icon' })
        .props()
        .onPress();
      expect(spyCloseModal).toHaveBeenCalled(); // this is passed
      expect(navigation.navigate).toHaveBeenCalled(); // this is not passed
    });
});

It looks like it gets stuck on the await calls. If I remove the await calls then it passes. Someone mentioned in another post to use .and.callThrough after spyOn but it gives me this error

Cannot read property 'callThrough' of undefined


回答1:


one of solution is to make your test async and run await (anything) to split your test into several microtasks:

it('should close the modal', async () => {
      const wrapper = renderComponent();
      component
        .find({ testID: 'close-icon' })
        .props()
        .onPress();
      await Promise.resolve();
      expect(navigation.state.params.onGoBack).toHaveBeenCalled(); 
      expect(navigation.navigate).toHaveBeenCalledWith("Main");
    });

I believe you don't need either .forceUpdate nor .spyOn on instance method. once navigation happens properly it does not matter by what internal method it has been called

more on microtask vs macrotask: https://abc.danch.me/microtasks-macrotasks-more-on-the-event-loop-881557d7af6f

alternative is to use macrotask(setTimeout(...., 0))

it('should close the modal', (done) => {
      const wrapper = renderComponent();
      component
        .find({ testID: 'close-icon' })
        .props()
        .onPress();
      setTimeout(() => {
        expect(navigation.state.params.onGoBack).toHaveBeenCalled(); 
        expect(navigation.navigate).toHaveBeenCalledWith("Main");
        done();
    });
}



回答2:


Yes, you're on the right track...the issue is that closeModal is asynchronous.

The await hasn't finished by the time execution returns to the test so this.props.navigation.navigate hasn't been called yet.

The test needs to wait for closeModal to complete before asserting that navigate has been called.

closeModal is an async function so it will return a Promise...

...and you can use the spy to retrieve the Promise it returns...

...then you can call await on that Promise in your test to make sure closeModal has completed before asserting that navigate has been called.

Here is a simplified working example to get you started:

import * as React from 'react';
import { shallow } from 'enzyme';

class MyClass extends React.Component {
  closeModal = async () => {
    await Promise.resolve();
    this.props.navigation.navigate('Main');
  }
  render() { return <div onClick={() => this.closeModal()}></div> }
}

test('MyClass', async () => {  // <= async test function
  const props = { navigation: { navigate: jest.fn() }};
  const wrapper = shallow(<MyClass {...props} />);
  const instance = wrapper.instance();
  const spyCloseModal = jest.spyOn(instance, 'closeModal');
  wrapper.find('div').simulate('click');
  expect(spyCloseModal).toHaveBeenCalled();  // Success!
  const promise = spyCloseModal.mock.results[0].value;  // <= get the Promise returned by closeModal
  await promise;  // <= await the Promise
  expect(props.navigation.navigate).toHaveBeenCalled();  // Success!
})

Note the use of mockFn.mock.results to get the Promise returned by closeModal.



来源:https://stackoverflow.com/questions/56654870/how-to-test-async-function-with-spyon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!