How to write test cases using jest and enzyme for connected components to my redux store?

点点圈 提交于 2019-12-24 00:29:27

问题


I want to write the test cases using jest, enzyme for my react component which connected with the redux store. The test case simply checks whether there is any "div" tag in the component or not. I have created a class component and connected it to the redux store.

I have tried writing a simple test case which should log the html of the component using wrapper.debug().

//Category component

import React, { Component } from 'react';
import { connect } from "react-redux";
import { Link } from 'react-router-dom';
import { getCategories, getSearchBoxValue, getSearchedCategories } from './actions';
import { InputText } from 'primereact/inputtext';
import { Button } from 'primereact/button';
import { Card } from 'primereact/card';
import { Checkbox } from 'primereact/checkbox';
import PropTypes from "prop-types";

class Category extends Component {

    constructor(props) {
        super(props);
        this.state = {                    
            searchedText: ''                
        };
    }

    componentDidMount() {        
        //dispatches action which gets all the categories
        this.props.getCategories();
    }

    componentWillReceiveProps(recievedProps) {
        this.setState({                   
            value: recievedProps.valueInSearchBox,           
        })
    }

    handleTextInputChange = value => {
        console.log("change: ", value.target.value);
        //checks that the value entered is not null or undefined
        if (value != "" || value != undefined) {
            this.setState({ searchedText: value.target.value });
        }
        else {
            this.setState({ searchedText: '' })
            this.props.getSearchedCategories('');
        }
    };

    onSearch = () => {        
        this.props.getSearchedCategories(this.state.searchedText);
    }

    render() {

        return (
            <>               
                <div>
                    <div className="searchInputs">
                        <h2>Hello</h2>
                        {/* InputText component of prime react */}
                        <InputText value={searchedText} onChange={this.handleTextInputChange} placeholder="Search..." />
                        {/* Button comopnent of prime react */}
                        <Button label="Go" className="p-button-secondary" onClick={this.onSearch} />
                    </div>                        
                </div>
            </>
        )
    }
}

const mapStateToProps = (state) => ({
    valueInSearchBox: state.categoryReducer.valueInSearchBox,   
    filteredCategoryData: state.categoryReducer.filteredCategoryData ? state.categoryReducer.filteredCategoryData : []
})

Category.propTypes = {
    filteredCategoryData: PropTypes.array,
    valueInSearchBox: PropTypes.string,
    getCategories: PropTypes.func,
    getSearchedCategories: PropTypes.func
};


export default connect(mapStateToProps, { getCategories, getSearchBoxValue, getSearchedCategories })(Category);

//Initial code for writing test cases

import React from "react";
import { shallow } from "enzyme";
import Category from './Category.js'
// import configureMockStore from 'redux-mock-store';

function renderCourseForm(args) {

    const defaultProps = {       
        valueInSearchBox: "",     
        filteredCategoryData: [],      
        getCategories: () => { },       
        getSearchedCategories: () => { }
    };
    const props = { ...defaultProps, ...args };
    console.log("defaultProps: ", defaultProps)
    return shallow(<Category {...props} />);
}
it("renders search Box and button", () => {
    const wrapper = renderCourseForm();
    console.log(wrapper.debug());
    console.log(wrapper.find("div").length);  
});

I expected the output as rendered html of the component, but the output is as shown below and the printed length gives the output 0.

<ContextConsumer>
    [function bound indirectRenderWrappedComponent]
</ContextConsumer>

Is this the correct way to write test cases using enzyme? I am not able to navigate to the component when from the test file, is there any mistake in importing the category component? What does [function bound indirectRenderWrappedComponent] mean while debugging the wrapper in my test code?

Solution:

import React from "react";
import { mount } from "enzyme";
import { Provider } from 'react-redux';
import Category from './Category.js'
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import store from "../configureStore";

function renderCourseForm() {
    return mount(
        <Provider store={store}>
            <Category />
        </Provider>
    );
}

describe('Container', () => {
    it('Checks the text of Search button', () => {
        const wrapper = renderCourseForm();       
        expect(wrapper.find("button").text()).toBe("Search");
    });

})

来源:https://stackoverflow.com/questions/56576006/how-to-write-test-cases-using-jest-and-enzyme-for-connected-components-to-my-red

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!