1
votes

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>
     );
    };
1
There is a mistake in tested component, ({ props }). It's (props). Also jest.fn((e) => (onIncrement = e)) doesn't make sense, why would you reassign spy function, not to mention that it's a constant? - Estus Flask
check now i reasssigned it now and passing object with values. and trying to get back the id value if clicked. const counter = {id:1, value:0}; 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(counter.id===1); }); - Syed Danish Ali Jr.
<Button {...{props}}> is an another mistake. It will pass props object with props key. It should be <Button {...props}> as it was before. The answer mentions it because <Button {...{props}}> is a way that could make ({ props }) work, but it shouldn't be like that any way. - Estus Flask
yeah thanks man i got the solution. - Syed Danish Ali Jr.

1 Answers

2
votes

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