lundi 19 août 2019

How can I test conditional rendering on a react component with react testing lib?

So this is the component I am attempting to test:

export const Profile: FC<Props> = props => {
  const { navigation, profileDetails, fetchProfileDetails } = props;

  useEffect(() => {
    !profileDetails && fetchProfileDetails();
  }, []);

  return (
    <ScrollView>
      {get(profileDetails, 'error') ? (
        <Error message={get(profileDetails, 'message') || 'Unknown Error'} />
      ) : (
        <UserContainer navigation={navigation} userDetails={profileDetails} />
      )}
    </ScrollView>
  );
};

As you may see there are a couple of components, Error and UserContainer components.

This is my test:

import React from 'react';
import { dummyUserInfo } from '../../shared/models/UserInfo.model';
import { Profile } from './Profile';
import { shallowRender } from '../../shared/services/testHelper';

const mockNavigation: any = { getParam: () => undefined };

const mockError: any = { profileDetails: { error: 'test error' } };

describe('Profile Scene', () => {
  it('renders error', () => {
    const tree = shallowRender(<Profile profileDetails={mockError} navigation={mockNavigation} />);
    expect(tree).toMatchSnapshot();
  });
});

And this is how the snapshot for the renders error test looks:

exports[`Profile Scene renders error 1`] = `
<ScrollViewMock>
  <UserContainer
    navigation={
      Object {
        "getParam": [Function],
      }
    }
    userDetails={
      Object {
        "profileDetails": Object {
          "error": "test error",
        },
      }
    }
  />
</ScrollViewMock>
`;

So is that a proper way to test that kind of things or is there a better way?

Aucun commentaire:

Enregistrer un commentaire