如何测试传递给组件的方法

时间:2019-04-19 18:16:43

标签: javascript reactjs jestjs enzyme

我一直在努力寻找准确解决该问题的方法,我一直在尝试处理模拟数据和各种不同的方法,但我仍在寻找在线解决方案。

我很好奇如何设置测试,以便检测到真实情况(CardTopic主题===“反应”),然后调用适当的功能。

测试

  it("should invoke renderReview if the local state topic equals 'React'", () => {
    wrapper = shallow(<CardTopic topic="React" />);
    wrapper.find("section").simulate("click");
    expect(wrapper.instance().handleClick).toEqual(renderReview);
  });

错误

TypeError: this.props.renderReview is not a function

      11 |   handleClick = () => {
      12 |     this.state.topic === "React"
    > 13 |       ? this.props.renderReview()
         |                    ^
      14 |       : this.props.renderNotFound();
      15 |   };
      16 |   render() {

1 个答案:

答案 0 :(得分:1)

简单修复。您只需要为组件提供一些mock function jest.fn()道具即可。

请阅读有关以下内容的更多信息:describe块以及beforeEachafterEach方法。

例如:

import React from "react";
import { shallow } from "enzyme"
import CardTopic from '../path/to/CardTopic";

// jest mocked functions -- defined here for ease of use throughout the test
const renderReview = jest.fn(); 
const renderNotFound = jest.fn();

// define any initial props (this.props) the component uses   
const initialProps = {
  renderReview,
  renderNotFound,
  ...etc
}

describe("Card Topic", () => {

  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<CardTopic {...initialProps } />); // this resets wrapper for each test (removes any state that was set)
  });

  afterEach(() => {
    renderReview.mockClear(); // resets the mock information (number of times it's been called);
    renderNotFound.mockClear(); // resets the mock information (number of times it's been called);
    wrapper.unmount(); // unmounts each wrapper instance after each test 
  });

  it("renders renderReview if the local state topic equals 'React'", () => {
    wrapper.setState({ topic: "React" }); // set wrapper's "topic" state
    wrapper.update(); // update the wrapper with this new state

    wrapper.instance().handleClick(); // invoke the method

    expect(renderReview).toHaveBeenCalledTimes(1); // expect a mock function to be called
    expect(renderNotFound).toHaveBeenCalledTimes(0); // not needed, but here for declarative purposes
  });

  it("renders renderNotFound if the local state topic does not equal 'React'", () => {
    wrapper.setState({ topic: "Redux" }); // set wrapper's "topic" state
    wrapper.update(); // update the wrapper with this new state

    wrapper.instance().handleClick(); // invoke the method

    expect(renderNotFound).toHaveBeenCalledTimes(1); // expect a mock function to be called
    expect(renderReview).toHaveBeenCalledTimes(0); // not needed, but here for declarative purposes
  });
});

如果您不想使用模拟功能,但想对实际功能进行测试,则需要导入这些功能并以与上述相同的方式提供它们。然后,如果这些函数改变了DOM,那么您将需要对DOM进行断言。