简体   繁体   中英

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

im newbie in jest/enzyme testing with react and im trying to test react Button Component by passing props and im getting this error Cannot read property 'onIncrement' of undefined .

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

You need to change this:

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

to this:

export const Button = (props) => {}

Otherwise:

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

Edit:

This should works:

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");
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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