Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  151] [ 2]  / answers: 1 / hits: 5296  / 4 Years ago, wed, december 9, 2020, 12:00:00

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

More From » reactjs

 Answers
4

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

[#2154] Thursday, December 3, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eden

Total Points: 730
Total Questions: 117
Total Answers: 117

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
eden questions
;