简体   繁体   English

使用Jest Enzyme在React中使用参数测试功能

[英]Testing functions with arguments in React with Jest Enzyme

I have a function named toggleFilter() in a react component which looks like this: 我在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]
                }
            }));
        }
    };

This function is being passed to the child components as : 该函数通过以下方式传递给子组件:

 <ChildComponent  toggleFilter={this.toggleFilter} />

So, i am trying to test this toggleFilter() function like this: 因此,我正在尝试像这样测试这个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" } });
});

But I get the error saying : 但我得到错误说:

TypeError: Cannot read property 'includes' of undefined

What may be causing the issue? 是什么原因引起的? Can someone please help me with this. 有人可以帮我吗

EDIT 1: I tried the below test case: 编辑1:我尝试以下测试用例:

expect(toggleFilterMockFn).toHaveBeenCalledWith(appliedFilter, "access");

But I get the below error : 但是我得到以下错误:

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.

You can't render a parent and test a child function like that. 您不能像这样渲染父对象并测试子函数。 Instead, you should render <FilterDropdownContent /> directly, and then write a test that simulates an event (like click) and checks to see if the function was called. 相反,您应该直接呈现<FilterDropdownContent /> ,然后编写一个模拟事件(如click)的测试,并检查是否调用了该函数。

Something like this for example: 例如:

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' } });
    });
  }):
});

In this example, clicking a link with the .toggle-filter class calls the function, but you should be able to adapt this to your specific implementation. 在此示例中,单击带有.toggle-filter类的链接将调用该函数,但是您应该能够.toggle-filter适应您的特定实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM