使用Redux和react-testing-library

时间:2019-01-21 04:28:56

标签: javascript reactjs redux react-redux react-testing-library

我是刚开始在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

任何指针,技巧或解决方案将不胜感激!

3 个答案:

答案 0 :(得分:2)

您的单元测试方法不正确。

使用redux-mock-store对Redux代码进行单元测试。

第1步:

import configureMockStore from 'redux-mock-store';

第2步:

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

第3步:

const component = shallow(<Sample store={store} />);

现在您的组件已准备好进行单元测试。

您可以在商店中设置用户,例如...

const store = mockStore({user:{..user object}});

现在使用快照测试或其他方式测试组件。我更喜欢快照测试。

expect(component).toMatchSnapshotTesting(); // this will test the complete component.

答案 1 :(得分:1)

您应该将组件包装在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();
  });
});

答案 2 :(得分:-1)

**Unable to Fire event using @testing-library**

// demo.test.js
    import React from 'react'
    import { Provider } from "react-redux";
    import '@testing-library/react/cleanup-after-each'
    import '@testing-library/jest-dom/extend-expect'

    import { render, fireEvent } from '@testing-library/react'

    // this is used to fire the event 
    // import userEvent from "@testing-library/user-event";

    //import 'jest-localstorage-mock';

    import ChangePassword from './ChangePassword';
    import configureMockStore from 'redux-mock-store';
    import thunk from 'redux-thunk';

    const middlewares = [thunk];
    const mockStore = configureMockStore(middlewares);


    test('test 1-> Update User password', () => {

      // global store
        const getState = {
            authUser :{
                user : {
                    email: "test@gmail.com",
                    id: 0,
                    imageURL: null,
                    name: "test Solutions",
                    roleId: 1,
                    roleName: "testRole",
                    userName: "testUserName"
                },
                loading: false,
                showErrorMessage: false,
                errorDescription: ""
            }

        }; // initial state of the store
       // const action = { type: 'LOGIN_USER' };
       // const expectedActions = [action];
       // const store = mockStore(getState, expectedActions);
        const onSaveChanges = jest.fn();
        const changePassword = jest.fn();
        const store = mockStore(getState);

        const { queryByText, getByLabelText, getByText , getByTestId , getByPlaceholderText, } = render(
            <Provider store={store}>
                <ChangePassword
                   onSaveChanges={onSaveChanges}
                   changePassword={changePassword}
                    />
            </Provider>,
        )

        // test 1. check the title of component 
        expect(getByTestId('updateTitle')).toHaveTextContent('Update your password');

        // test 2. chekck the inputfile 
        expect(getByPlaceholderText('Old Password')) //oldpassword
        expect(getByPlaceholderText('New Password')) //newpassword
        expect(getByPlaceholderText('Confirm New Password')) //confpassword

        // change the input values
        fireEvent.change(getByPlaceholderText("Old Password"), {
          target: { value: "theOldPasword" }
        });

        fireEvent.change(getByPlaceholderText("New Password"), {
          target: { value: "@Ab123456" }
        });

        fireEvent.change(getByPlaceholderText("Confirm New Password"), {
          target: { value: "@Ab123456" }
        });

        // check the changed input values 
        expect(getByPlaceholderText('Old Password').value).toEqual("theOldPasword");
        expect(getByPlaceholderText('New Password').value).toEqual("@Ab123456");
        expect(getByPlaceholderText('Confirm New Password').value).toEqual("@Ab123456");

        expect(getByText('Save Changes')); // check the save change button 

         // calling onSave function 
        //fireEvent.click(getByTestId('savechange'))  
       // userEvent.click(getByText('Save Changes'));

    })