使用Redux和react-testing-library测试React组件

6

我是一名新手,想要测试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))
})  

用户属性的值始终为未定义。我已经尝试过几种方法重新编写了代码,但似乎无法解决这个问题。如果我直接将用户数据作为 prop 传递给测试中的示例组件,则仍会被解析为未定义。
我正在学习来自官方文档的教程和示例,比如这个:https://github.com/kentcdodds/react-testing-library/blob/master/examples/tests/react-redux.js 非常感谢您能提供任何指针、提示或解决方案!

似乎你没有传递或定义一个initialState - dangerismycat
你解决了吗,@Charklewis? - Ashok
很遗憾,我没有。现在我通常采用上下文/约简器架构,因此我不太可能在不久的将来重新访问这个问题。 - Charklewis
你是否考虑过在测试中使用 https://github.com/reduxjs/redux-mock-store 来轻松模拟你的 store? - Florian Motteau
2个回答

2
你应该将组件包裹在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();
  });
});

-4
**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'));

    })

这是对问题的回答吗?为什么有这么多死代码(被注释掉的代码)?您能否提供一些解释,说明那段代码如何回答了这个问题? - Laurenz Albe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接