I have follow React component which render as a child in parent component and props are passed:

<Component 
    localStorageValue={'test-walue'} 
    requestDataFunc={getData}
    requestUserData={getUserData} 
    expectedResponseKey={'key'} 
    dataType={'test}
    activePage={'index'} 
    saveData={this.setData} 
/>

so requestDataFunc is a funtion which passed to component and runned in componentDidMount :

componentDidMount() {
  requestDataFunc().then(({ data }) => {
      const { selectedDataItems } = this.state;
      const expectedResponseData = data[expectedResponseKey];
      let interimDataArr = [];
      expectedResponseData.forEach((item) => {
        interimDataArr = [...interimDataArr, {
          ...item,
          active: selectedDataItems.length ? selectedDataItems.some((selectedItemId) => selectedItemId === item.id) : false,
        }];
      });
}

but when I run my tests, I got:

TypeError: Cannot read property 'then' of undefined

requestDataFunc().then(({ data }) => {
    const { selectedDataItems } = this.state;
    const expectedResponseData = data[expectedResponseKey];
    let interimDataArr = [];

I just starting to test render component:

describe('correct component render', () => {
  const defaultProps = {
    localStorageValue: 'test-walue',
    requestDataFunc: jest.fn(),
    requestUserData: jest.fn(),
    expectedResponseKey: 'key',
    dataType: 'test',
    activePage: 'index',
    saveData: jest.fn(),
  };

  const wrapper = shallow(<ComponentName { ...defaultProps } />);

  test("render component", () => {
    expect(wrapper.length).toEqual(1);
  });


});

I suppose that I need to mock somehow request and data that this request should receive. How to do this correctly?

2 Answers

2
Shruti On Best Solutions

Have you tried mocking promise as below:

var mockPromise = new Promise((resolve, reject) => {
    resolve(<mock response similar to actual promise response>);
});
describe('correct component render', () => {
      const defaultProps = {
        localStorageValue: 'test-walue',
        requestDataFunc: jest.fn().mockReturnValueOnce(mockPromise),
        requestUserData: jest.fn(),
        expectedResponseKey: 'key',
        dataType: 'test',
        activePage: 'index',
        saveData: jest.fn(),
      };

      const wrapper = shallow(<ComponentName { ...defaultProps } />);

      test("render component", () => {
        expect(wrapper.length).toEqual(1);
      });
});
0
Ivan V. On

Axios get method returns a promise, so you when you mock that method you also need to return a Promise

jest.fn(() => Promise.resolve({}))

More on Jest async mocking

Relevant answer from SO