【问题标题】:How to test a function in jest and enzyme which is being called inside a React component如何测试在 React 组件中被调用的 jest 和酶函数
【发布时间】:2018-10-24 07:14:28
【问题描述】:

我有一个看起来像这样的函数:

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);

谁能告诉我我哪里出错了?

【问题讨论】:

  • 请添加更多详细信息。

标签: javascript reactjs tdd enzyme jestjs


【解决方案1】:

在我看来,props.appliedFilterList 返回未定义,因此在尝试评估 props.appliedFilterList[filterType] 时,您会收到以下错误:“TypeError: Cannot read property 'access' of undefined”。

你需要将applyFilterList作为一个prop传递。

const appliedFilterList = // 你的 appliedFilterList 实现

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

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 2018-03-25
    • 2020-07-15
    • 1970-01-01
    • 2018-09-28
    • 2020-02-25
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多