如何用玩笑测试反应组件中的箭头函数调用?

How to test arrow function calling in react component with jest?

我是 jest/enzyme 的新手,正在使用 React 进行测试,我正在尝试通过传递道具来测试 React 按钮组件,但我收到此错误 无法读取 属性 'onIncrement'未定义.

describe("Name of the group", () => {
  const counter = 'pc';
  const onIncrement = jest.fn();
  const props = {
    onIncrement,
    counter
};
it("should be clicked ", () => {
  const button = shallow(<Button {...{props}}>Increment</Button>);
  button.find(".increment").simulate("click");
  expect(button).toHaveBeenCalledWith('pc');
  });
  });

   import React from "react";
   export const Button = ( props ) => {
     return (
       <button
        id="inc"
        className="increment"
        onClick={() => props.onIncrement(props.counter)}
       >
        Increment
       </button>
     );
    };

你需要改变这个:

export const Button = ({ props }) => {} // component has a property called props

对此:

export const Button = (props) => {}

否则:

// it is not recommended
const button = shallow(<Button {...{props}}>Increment</Button>);

编辑:

这应该有效:

export const Button = (props) => {
  return (
    <button
     id="inc"
     className="increment"
     onClick={() => props.onIncrement(props.counter)}
    >
     Increment
    </button>
  );
 };
describe("Name of the group", () => {
  const counter = "pc";
  const props = {
    onIncrement: jest.fn(),
    counter,
  };

  it("should ", () => {
    const button = shallow(<Button {...props}>Increment</Button>);
    button.find(".increment").simulate("click");
    expect(props.onIncrement).toHaveBeenCalledWith("pc");
  });
});