Reputation: 25
I'm new to Jest and react-testing-library, so hopefully the solution to this is straight forward.
What is the proper way to test the value returned through the 'onChange' prop?
describe("Component.js", () => {
test("return correct data", () => {
render(
<Component
onChange={(value) => console.log(value)}
/>
);
});
});
I would like to do something like this for 'value'.
expect(value).toBe(50);
For the sake of simplicity, let's say Component.js looks something like this.
const Component = ({onChange}) => {
return (
<button onClick={() => onChange(50)}></button>
)
}
Upvotes: 0
Views: 79
Reputation: 3892
You could try something like:
const Component = ({onChange}) => {
return (
<button onClick={() => onChange(50)}>CustomButton</button>
)
}
describe("Component.js", () => {
test("return correct data", () => {
const onChangeHandler = jest.fn();
render(
<Component onChange={onChangeHandler} />
);
fireEvent.click(
screen.getbyText(/CustomButton/)
);
expect(onChangeHandler).toBeCalledWith(50);
});
});
The above may need modifications to be adopted to your use case.
Upvotes: 2
Reputation: 2422
just pass the component a mock function and test if it was called when the button is changed (though I assume for a button you would use onClick). You may need to add a testId or some way to target the button in your component as well.
describe("Component.js", () => {
test("return correct data", () => {
const spy = jest.fn();
render(
<Component
onChange={spy}
/>
);
fireEvent.change(screen.getByTestId('button'));
expect(spy).toHaveBeenCalledWith(50);
});
});
and the component
const Component = ({onChange}) => {
return (
<button
data-testid = 'button'
onClick={() => onChange(50)}></button>
)
}
Upvotes: 0