I want to test this function with React Testing Library this error
export default function capitalizeFirstLetter(string: string)
{
return string.charAt(0).toUpperCase() string.slice(1);
}
but I got
TypeError: Cannot read properties of undefined (reading 'charAt')
CodePudding user response:
One problem I see is that your function will fail when empty/null/undefined
value is passed and you need a guard for that. And that is why you need a test for.
As an example, I'd test this function as follows
// Should be in another file
function capitalizeFirstLetter(string: string) {
if (!string) return '';
return string.charAt(0).toUpperCase() string.slice(1);
}
describe('capitalizeFirstLetter', () => {
it('should return "Hello"', () => {
expect(capitalizeFirstLetter('hello')).toBe('Hello');
});
it('should return "Hi"', () => {
expect(capitalizeFirstLetter('Hi')).toBe('Hi');
});
it('should not fail when undefined/null or empty value is passed', () => {
expect(capitalizeFirstLetter(undefined)).toBe('');
expect(capitalizeFirstLetter(null)).toBe('');
expect(capitalizeFirstLetter('')).toBe('');
});
});
Or you can use describe.each with the list of payloads.