如何用Jest内的另一个功能测试功能?

时间:2018-10-12 14:25:27

标签: javascript reactjs jestjs enzyme

我刚刚开始学习测试以了解反应并在这一刻陷入困境。

这是我的功能:

private handleCountyItemClick = (
    e: React.FormEvent<HTMLButtonElement>
  ): void => {
    const { countries } = this.props.countriesRed;
    const selectedId: number = parseFloat(e.currentTarget.dataset.value);
    const foundCountry = countries.find(
      (country: Country, i: number) => i === selectedId
    );
    if (foundCountry) {
      this.props.CountyItemClick(foundCountry);
      this.props.clearInput();
      this.setState({
        dropdownOpen: false,
        fullWidthFullHeightElHeight: 54
      });
      this.countriesListItems.current.style.height = "";
      scrollIt(this.props.countriesRootEl.current, 300, "easeOutQuad", () =>
        enableBodyScroll(this.countriesListItems.current)
      );
    }
  };

然后,我编写了此测试,但出现错误:

it("should update the count by 1 when invoked by default", () => {
    const wrapper = shallow(component);
    const instance = wrapper.instance();
    instance.handleCountyItemClick({
      currentTarget: { dataset: { value: 1 } }
    });
  });

错误:

TypeError: _this.props.CountyItemClick is not a function

如您所见,在我的函数中,我使用Redux的另一个函数,并且此错误涉及Redux的函数。我不知道下一步该怎么做! 我需要做什么?如何进行?

1 个答案:

答案 0 :(得分:2)

似乎您需要嘲弄道具。

let props;
let wrapper;

beforeEach(() => {
  props = {
    CountyItemClick: jest.fn(),
  };
  wrapper = shallow(<Component {...props} />);
});

it("should update the count by 1 when invoked by default", () => {
  const wrapper = shallow(component);
  const instance = wrapper.instance();
  instance.handleCountyItemClick({
    currentTarget: { dataset: { value: 1 } }
  });

  expect(props.CountyItemClick).toHaveBeenCalled();
});