Test React Component с использованием Redux и реагировать на тестирование библиотеки - PullRequest
0 голосов
/ 21 января 2019

Я новичок в тестировании компонентов, подключенных к редуктору в React, и пытаюсь понять, как их тестировать.

В настоящее время я использую реагирующую библиотеку и испытываю проблемы с настройкой функции renderWithRedux для правильной настройки приставки.

Вот пример компонента:

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

Любые указатели, советы или решения будут с благодарностью!

Ответы [ 2 ]

0 голосов
/ 09 августа 2019
**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'));

    })
0 голосов
/ 21 января 2019

Ваш подход к модульному тестированию не верен.

Используйте redux-mock-store для модульного тестирования кода избыточного кода.

Шаг 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.
...