I’ve an input component and I’d like to create unit tests for it. I’m having few errors and I can’t fix it. I already see in few blogs but I don’t understand how to resolve it. I’m trying to improve my knowledge in unit tests, but it’s complicated.
Here’s my code I put into codesandbox
I don’t understand why I’ve this error, because I don’t have any boolean parameter. Can u tell me how to resolve it?
import React from 'react';
import { render, screen } from '@testing-library/react';
import TextInput from './TextInput';
import { TextInputProps } from 'src/types';
describe('Text Input', function () {
it('should render default', function () {
const props: TextInputProps = {
change(): void {},
value: '',
placeholder: 'Full Name',
variant: 'neutral',
};
render(<TextInput {...props} />);
expect(screen.getByRole('textbox')).toBeInTheDocument();
expect(screen.getByRole('textbox')).toHaveAttribute(
'placeholder',
'Full Name'
);
expect(screen.getByRole('textbox')).toHaveAttribute('value', '');
});
});
import React from 'react';
import { TextInputProps } from 'src/types';
import './index.scss';
const TextInput = ({
value,
placeholder,
type = 'text',
variant,
change,
}: TextInputProps) => {
const inputVariant = `input-field ${
variant === 'highlight' ? 'highlight' : ''
}`;
return (
<div className="content-input">
<input
className={inputVariant}
value={value}
placeholder={placeholder}
type={type}
onChange={change}
/>
</div>
);
};
export default TextInput;
import { ChangeEventHandler } from 'react';
export interface TextInputProps {
value: string;
placeholder: string;
type?: 'text' | 'password' | 'email';
variant: 'neutral' | 'highlight';
change: ChangeEventHandler<HTMLInputElement>;
}
2
Answers
The error you’re encountering is related to the change prop in your
TextInput
component. The change prop is defined as a `ChangeEventHandler. However, in your test code, you’re providing an empty function for the change prop, which doesn’t match the expected type.To resolve this error, you can provide a valid function that handles the change event in your test code. Here’s an example of how you can modify your test code:
Use a .tsx file, not a .ts one.
On the example you sent, I was able to reproduce the error, then noticed you were using a .ts file. Rename it to .tsx and the error is gone.