首页 > 解决方案 > 测试 React 组件方法和 mapDispatchToProps

问题描述

我正在为我的 React 组件编写一些测试。

import { withRouter } from 'react-router-dom';

class CityFilter extends React.Component {

    handleSelect = selectedCity => {
        this.props.cityFilterChanged(selectedCity)
    }

    render() {
        return(
            <Dropdown data={this.props.cityData}
                      onSelect={this.handleSelect}
            />
        )
    }

    export function mapStateToProps(state) {
        return { cityData: state.Cities.cityData }
    }

    export function mapDispatchToProps(dispatch) {
        return bindActionCreators({
            cityFilterChanged
        }, dispatch);
    }
}

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CityFilter));

jest我使用and运行了以下测试enzyme

import cityFilterChanged from '../../actions/cityFilterChanged';
import DropDown from '../components/DropDown';
import {mapDispatchToProps, mapStateToProps } from '../CityFilter';

describe('Test cases for CityFilter Component', () => {
    const dummyCityData = []; // contains lists of cities
    const wrapper = mount(
        <CityFilter
            cityData={dummyCityData}
        />);

    wrapper.instance().handleSelect = jest.fn();

    it('calls handleSelect on selecting a value', () => {
        wrapper.find('checkbox').first().simulate('click');
        expect(wrapper.instance().handleSelect).toBeCalled(); // passes
    });

    it('tests mapDispatchToProps function', () => {
        expect(mapDispatchToProps()).toEqual({
            cityFilterChanged
        });
    })
});

当我检查CityFilter组件的代码覆盖率时(在运行覆盖率命令之后),我发现它handleSelect没有被测试覆盖/执行,即使有关的测试toBeCalled通过了。我的目标是百分百的测试覆盖率,那么如何确保我的测试成功运行handleSelect

此外,有关的测试mapDispatchToProps失败,给出错误:

Expected: {"cityFilterChanged": [Function anonymous]}
Received: serializes to the same string

我怎样才能解决这个问题?

标签: javascriptreactjsjestjsenzyme

解决方案


好吧,您是handleSelect在模拟而不是直接对其进行测试,因此您可以尝试删除模拟并测试在调用时会handleSelect产生所需的效果:

describe('Test cases for CityFilter Component', () => {
    const dummyCityData = []; // contains lists of cities
    const wrapper = mount(
        <CityFilter
            cityData={dummyCityData}
        />);

    it('calls handleSelect on selecting a value', () => {
        wrapper.find('checkbox').first().simulate('click');
        // Assert that cityFilter value has been updated
    });
});

推荐阅读