Skip to content

Test custom async hooks #2012

@helabenkhalfallah

Description

@helabenkhalfallah

I use Enzyme version 3.8.0.

// functional component
const UsersList = ({ onItemSelected, }) => {
  // async service fetch hooks
  const url = 'service-url';
  const { error, loading, data, } = useService(Service, url, {
    amount: 0,
  });

  return (
    <Fragment>
      <div className="user-list">
          {
            data.map(user => (
              <UserItem
                key={user.id}
                user={user}
                onItemSelected={onItemSelected}
              />
            ))
          }
        </div>
    </Fragment>
  );
};

My useService make an async call to get user list data.

Test :

jest.mock('axios');
it('Should Mount Component & Display Data', async () => {
    // mock result
    axiosMock.get.mockResolvedValue(UserListMock);
    
    // mount component
    const wrapper = mount(<UserList />);

    // wait to have data
    await expect(wrapper.state().data).to.not.be.null;

    // test
    expect(wrapper.find('h2').first().text()).toEqual('Mock Title');
  });

But I have this error :
ReactWrapper::state() can only be called on class components

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions