I\'m relatively new to Jest and testing in general. I have a component with an input element:
import * as React from \"react\";
export interface inputProps{
For those testing using TypeScript (and borrowing from the answers above), you'll need to perform a type coercion (as React.ChangeEvent
) to ensure that the linter can view the signature as being compatible:
React file
export class InputBox extends React.Component {
onSearch(event: React.ChangeEvent){
event.preventDefault();
//the actual onclick event is in another Component
this.props.onSearch(event.target.value.trim());
}
render() {
return (
);
}
}
Test file
it('should call onChange prop', () => {
const onSearchMock = jest.fn();
const event = {
target: { value: 'the-value' }
} as React.ChangeEvent;
const component = enzyme.shallow( );
component.find('input').simulate('change', event);
expect(onSearchMock).toBeCalledWith('the-value');
});
or alternatively
it('should call onChange prop', () => {
const onSearchMock = jest.fn();
const event = {
target: { value: 'the-value' }
} as React.ChangeEvent;
const component = enzyme.mount( );
const instance = component.instance();
instance.onSearch(event);
expect(onSearchMock).toBeCalledWith('the-value');
});