jeudi 30 juillet 2020

Test connected functional component with props - Redux & React Testing Library

I am attempting to test the returned render of my React component via its 2 different routes, depending on the presence of a particular featureToggle that will either be set to true or false.

import React from 'react';
import {connect} from "react-redux";

const mapStateToProps = (state) => ({
    featureToggle: (state.featureToggle && typeof state.featureToggle === 'object') ? state.featureToggle : null,
});

const MyComponent = ({featureToggle}) => {
    if (!featureToggle.myToggle) {
        return (
            <div>
               // One version of the component
            </div>
        );
    }

    return (
        <div>
            // Another version of the component
        </div>
    );
}

export default connect(mapStatesToProps)(MyComponent)

However I am struggling to get to grips with React Testing Library and React Redux. So far I have...

import React from 'react';
import MyComponent from "./MyComponent";
import {Provider} from "react-redux";
import {render} from "@testing-library/react";
import configureStore from 'redux-mock-store';

const mockStore = configureStore();

const getToggle = value => {
    return {myToggle: value};
}

let store;
let provider;
let rendered;

describe('MyComponent', () => {
    describe('Should render route 1 with toggle off', () => {
        store = mockStore(getToggle(false);

        beforeEach(() => {
            provider = <Provider store={store}><MyComponent /></Provider>;
            rendered = render(provider);
        })
   
        it('Should render fallback title', () => {
            expect(rendered.getByTestId('title').textContent).toBe('Toggle Off Title');
        });
    });

    describe('Should render second route with toggle on', () => {
        store = mockStore(getToggle(true);

        beforeEach(() => {
            provider = <Provider store={store}><MyComponent featureToggle={getToggle(true)} /></Provider>;
            rendered = render(provider);
        });

        it('Should render live title', () => {
            expect(rendered.getByTestId('title').textContent).toBe('Toggle On Title');
        });
    });
});

However, running this test file I receive:

TypeError: Cannot read property 'myToggle' of null

      10 | 
      11 | const MyComponent = ({featureToggle}) => {
    > 12 |     if (!featureToggle.myToggle) {
         |                        ^

Aucun commentaire:

Enregistrer un commentaire