如何测试在React组件中调用的jest和酶中的函数

时间:2018-05-14 15:02:17

标签: javascript reactjs tdd enzyme jest

我的功能如下:

const generateCheckboxes = (array, filterType) => {
    return array.map((filter, i) => {
        if (!isNullOrUndefined(filter) && filter !== "") {
            const applied = props.appliedFilterList[filterType].includes(filter);
            return (
                <Row key={i} noLine={i === 0}>
                    <Checkbox checked={applied} onClick={() => props.toggleFilter(filterType, filter)}>
                        {filter}
                    </Checkbox>
                </Row>
            );
        }
        return false;
    });
};

我将其称为:

 return (
        <div>
            <div>
                {generateCheckboxes(props.accessFilters, "access")}
            </div>
            <div>
                {generateCheckboxes(props.bandwidthFilters, "bandwidth")}
            </div>
        </div>
    );

我想使用Jest和Enzyme测试函数generateCheckboxes()。所以,我尝试编写以下测试用例:

const accessFilters = ["Access Type Of The Service", { length: 1 }];
const bandwidthFilters = ["the allowed band width", "the allowed band width", { length: 2 }];

describe("test the component", () => {
    const wrapper = mount(<FilterDropdownContent accessFilters={accessFilters} bandwidthFilters={bandwidthFilters} />);

    it("checks the generateCheckBoxes function", () => {
        expect(wrapper.instance.generateCheckboxes(accessFilters, "access").toBe(true));
    });
});

但是我收到以下错误:

 TypeError: Cannot read property 'access' of undefined

      at array.map (src/site-product/components/FilterDropdownContent.js:12:105)
          at Array.map (<anonymous>)
我得到错误的组件中的函数的

和第12行是:

 const applied = props.appliedFilterList[filterType].includes(filter);

任何人都可以告诉我哪里出错了?

1 个答案:

答案 0 :(得分:0)

对我而言,似乎props.appliedFilterList返回undefined,因此当尝试evauluate props.appliedFilterList [filterType]时,您会收到该错误:“TypeError:无法读取未定义的属性'access'。

您需要将appliedFilterList作为道具传递。

const appliedFilterList = //您的appliedFilterList实现

const wrapper = mount(<FilterDropdownContent accessFilters={accessFilters} bandwidthFilters={bandwidthFilters} appliedFilterList={appliedFilterList}/>);
相关问题