繁体   English   中英

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

[英]Test React Component using Redux and 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/测试/react-redux.js

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

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

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

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

第1步:

import configureMockStore from 'redux-mock-store';

第2步:

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

第三步:

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

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

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

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

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

expect(component).toMatchSnapshotTesting(); // this will test the complete component.
**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'));

    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM