我在反应组件中有一个名为 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.
您无法像这样渲染父函数并测试子函数。相反,您应该直接渲染
<FilterDropdownContent />
,然后编写一个测试来模拟事件(如单击)并检查该函数是否被调用。
例如这样的事情:
import React from 'react';
import { shallow } from 'enzyme';
describe('<FilterDropdownContent />', () => {
let wrapper, toggleFilter;
beforeEach(() => {
toggleFilter = jest.fn();
wrapper = shallow(
<FilterDropdownContent
toggleFilter={toggleFilter}
/>
);
});
describe('when clicking the .toggle-filter button', () => {
it('calls `props.toggleFilter()` with the correct data', () => {
wrapper.find('.toggle-filter').simulate('click');
expect(toggleFilter).toHaveBeenCalledWith({ target: { value: 'someValue' } });
});
}):
});
在此示例中,单击带有
.toggle-filter
类的链接会调用该函数,但您应该能够根据您的具体实现进行调整。