Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test React Component using Redux and react-testing-library

I am new to testing redux connected components in React and trying to figure out how to test them.

Currently I'm using react-testing-library and having trouble setting up the my renderWithRedux function to correctly setup redux.

Here is a sample component:

import React, { Component } from 'react'
import { connect } from 'react-redux'

class Sample extends Component {

    constructor(props) {
        super(props);
        this.state = {
           ...
        }
    }

    componentDidMount() {
        //do stuff
        console.log(this.props)
    }


    render() {

        const { user } = this.props

        return(
            <div className="sample">
                {user.name}
            </div>
        )

    }

}

const mapStateToProps = state => ({
    user: state.user
})

export default connect(mapStateToProps, {})(Sample);

Here is a sample test:

import React from 'react';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { render, cleanup } from 'react-testing-library';
import Sample from '../components/sample/'

const user = {
    id: 1,
    name: "John Smith"
}}

function reducer(state = user, action) {
    //dont need any actions at the moment
    switch (action.type) {
      default:
        return state
    }
}

function renderWithRedux(
    ui,
    { initialState, store = createStore(reducer, initialState) } = {}
    ) {
    return {
        ...render(<Provider store={store}>{ui}</Provider>),
        store,
    }
}

afterEach(cleanup)

test('<Sample> example text', () => {
    const { getByTestId, getByLabelText } = renderWithRedux(<Sample />)
    expect(getByText(user.name))
})  

The user prop value always results as undefined. I have re-written this a couple of ways but can't seem to get it to work. If I pass the user data directly as a prop to Sample component in the test, it still resolves to be undefined.

I am learning from the tutorials and examples via the offical docs, like this one: https://github.com/kentcdodds/react-testing-library/blob/master/examples/tests/react-redux.js

Any pointers, tips or solutions would be greatly appreciated!

like image 537
Charklewis Avatar asked Jan 21 '19 04:01

Charklewis


People also ask

How do I test Redux connected components React testing library?

js import React from 'react'; import { render } from '@testing-library/react'; import { createStore } from 'redux'; import { Provider } from 'react-redux'; // Replace this with the appropriate imports for your project import { reducer, reducerInitialState } from './myReduxStore'; const renderConnected = ( ui, { ...

How do you test the components of a React?

There are a few ways to test React components. Broadly, they divide into two categories: Rendering component trees in a simplified test environment and asserting on their output. Running a complete app in a realistic browser environment (also known as “end-to-end” tests).

What is the difference between enzyme and React testing library?

If you want mimic real-world user interactions, the React Testing Library is the way to go because you can do the same with fireEvent functions. Meanwhile, Enzyme is better suited to situations where you have to match the state of React or some other function with state.


1 Answers

You should wrap the component inside Provider, here is the simple example

import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Provider } from "react-redux";
import configureMockStore from "redux-mock-store";

import TestedComponent from '../index';

const mockStore = configureMockStore();
const store = mockStore({});

const renderTestedComponent = () => {
  return render(
    <Provider store={store}>
      <TestedComponent />
    </Provider>
  );
};

describe('test TestedComponent components', () => {
  it('should be render the component correctly', () => {
    const { container } = renderTestedComponent();

    expect(container).toBeInTheDocument();
  });
});
like image 136
Harry Andriyan Avatar answered Sep 28 '22 07:09

Harry Andriyan