首页 > 解决方案 > 使用 Redux 和 react-testing-library 测试 React 组件

问题描述

我是在 React 中测试 redux 连接组件并试图弄清楚如何测试它们的新手。

目前我正在使用 react-testing-library 并且无法设置我的 renderWithRedux 函数以正确设置 redux。

这是一个示例组件:

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);

这是一个示例测试:

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))
})  

用户属性值始终未定义。我已经用几种方法重写了这个,但似乎无法让它工作。如果我在测试中直接将用户数据作为道具传递给 Sample 组件,它仍然解析为未定义。

我正在通过官方文档从教程和示例中学习,例如:https : //github.com/kentcdodds/react-testing-library/blob/master/examples/tests/react-redux.js

任何指针、提示或解决方案将不胜感激!

标签: javascriptreactjsreduxreact-reduxreact-testing-library

解决方案


您应该将组件包装在 Provider 中,这是一个简单的示例

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();
  });
});

推荐阅读