Test with Enzyme

UI testing with Enzyme and other UI renderers

In order to test components with enzyme or other library that renders actual components you need to do following:

  • prepare test environemt

 beforeEach(() => {
    const initialState = {
        todos: [
            { id: 1, name: 'test', description: 'test' },
            { id: 2, name: 'test', description: 'test description' },
        ],
    };

    ReactStateTestBed.setTestEnvironment(new ImmerDataStrategy());
    ReactStateTestBed.useComponentRenderer = true;
    ReactStateTestBed.strictActionsCheck = false;
    ReactStateTestBed.createActions(TodosStateActions, initialState, ['todos']);

    wrapper = shallow(<Todos />);
});
  • useComponentRenderer- since react-state unit testing is designed with posibility to test JUST component business logic. For this we do not want forceUpdate is called on state change. However if you testing with renderers like Enzyme you would like your components are updated after state change. So with this flag you configuring TestBed to call forceUpdate on state change.

  • strictActionCheck - since component template can have multiple components and we are not creating actions for each of them - we configure TestBed to not throw an error if actions for component were not found. It is optional if:

    • You have just one level component

    • You provide all actions to all child components

  • createActions - creates actions for top component with initial state. All nested actions of nested components will be created automatically. tip: initialState, that top components was created with, should contain structure that matches nested component actions paths. For exmple: if your nested component actions path is @InjectStore([''${stateIndex}]) and your top component template is: <TodosDescription statePath={this.statePath} stateIndex={1}></TodoDescription> you need to make sure that initial state has array of todos with 2 items Also you can ovveride each action of nested components by creating custom ones by calling createActions. ReactStateBed will look in list of custom actions before trying to create real ones.

and write your spec

it('should change child description on button click', () => {
    expect(wrapper.render().find('.description').text()).toEqual('test description');
    
    const button = wrapper.find('.button');
    button.simulate('click');
    
    expect(wrapper.render().find('.description').text()).toEqual('changed description');
});

Last updated