Skip to content

Latest commit

 

History

History
63 lines (58 loc) · 2.07 KB

components-state-testing.mo.md

File metadata and controls

63 lines (58 loc) · 2.07 KB

[MO] Test your React and React Native components' state with Jest (without Enzyme) (~35 min)

Prerequisites (~5 min)

  • Have Jest installed
  • On React, follow the Jest documentation
  • On React Native, it's already done (if needed, jest doc)

Steps (~30 min)

  • Create a simple test:
describe('ComponentToTest', () => {
  it('should test a simple true === true', () => {
    expect(true).toBe(true);
  });
});
  • Import the necessary packages and your component:
import React from 'react';
import renderer from 'react-test-renderer';

import ComponentToTest from './ComponentToTest.component';
  • Add the first test of your component, and remove the true === true
    • Render your component with react-test-renderer, it will transform your component in a JavaScript object instance, which you will be able to test, accessing its state, triggering its methods:
    describe('ComponentToTest', () => {
      const props = {};
    
      const component = renderer.create(
        <ComponentToTest
          props={props}
        />
      );
      //...
    });
    • Use this instance in your it test, the property getInstance() allows you to access all the properties of the component class. Now you can test your initial state:
    describe('ComponentToTest', () => {
      // ...
      it('should init the state', () => {
        expect(component.getInstance().state).toEqual({
          fakeStatus: 'init',
        });
      });
    });
  • Add new tests, faking a user action and the impact it has on the component state:
describe('ComponentToTest', () => {
  // ...
  it('should set the component fakeStatus to "inProgress"', () => {
    component.getInstance().onButtonPress();
    expect(component.getInstance().state).toEqual({
      fakeStatus: 'inProgress',
    });
  });
  // ...
});