我在react组件中有一个名为**toggleFilter()**的函数,如下所示:
toggleFilter = (filterType, filterName) => {
const filterApplied = this.state.appliedFilterList[filterType].includes(filterName);
if (filterApplied) {
//Remove the applied filter
this.setState(prevState => ({
appliedFilterList: {
...prevState.appliedFilterList,
[filterType]: prevState.appliedFilterList[filterType].filter(filter => filter !== filterName)
}
}));
} else {
//Add the filter
this.setState(prevState => ({
appliedFilterList: {
...prevState.appliedFilterList,
[filterType]: [...prevState.appliedFilterList[filterType], filterName]
}
}));
}
};
此函数作为以下函数传递给子组件:
<ChildComponent toggleFilter={this.toggleFilter} />
因此,我尝试测试这个toggleFilter()函数,如下所示:
it("checks for the function calls", () => {
const toggleFilterMockFn = jest.fn();
const component = shallow(
<ProductList
headerText="Hello World"
productList={data}
paginationSize="10"
accessFilters={["a 1", "a 2"]}
bandwidthFilters={["b 1", "b 2"]}
termsFilters={["t 1", "t 2"]}
appliedFilterList={appliedFilter}
toggleFilter={toggleFilterMockFn}
/>
);
component.find(FilterDropdownContent).prop("toggleFilter")({ target: { value: "someValue" } });
});
型
但我得到的错误说:TypeError: Cannot read property 'includes' of undefined
什么可能导致这个问题?谁能帮我一下吗?
**编辑1:**我尝试了以下测试用例:
expect(toggleFilterMockFn).toHaveBeenCalledWith(appliedFilter, "access");
但我得到以下错误:
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
[{"access": ["Access Type Of The Service"], "bandwidth": ["the allowed band width ", "the allowed band width"], "term": ["term associated with the service"]}, "access"]
But it was not called.
1条答案
按热度按时间zujrkrfu1#
你不能像这样呈现一个父函数并测试一个子函数,相反,你应该直接呈现
<FilterDropdownContent />
,然后编写一个测试来模拟一个事件(比如click)并检查该函数是否被调用。比如说这样的事情:
在本例中,单击
.toggle-filter
类的链接将调用该函数,但您应该能够使其适应您的特定实现。