在React with Jest Enzyme中使用参数测试函数

时间:2018-05-22 09:55:38

标签: javascript reactjs tdd jestjs enzyme

我在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 个答案:

答案 0 :(得分:0)

您不能像这样渲染父级和测试子级功能。相反,您应该直接渲染<FilterDropdownContent />,然后编写一个模拟事件(如click)并检查是否调用了该函数的测试。

例如这样的东西:

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类的链接将调用该函数,但是您应该能够使它适应您的特定实现。