0

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')
2
  • 1
    In your test function where you call this you pass nothing perhaps or undefined value. Can you show how you test it? Commented Aug 5, 2022 at 15:42
  • Given you're using TypeScript, how did the compiler let you do capitalizeFirstLetter()? Is that actually a realistic case to deal with (and if so what should the behaviour be)? And given that this is a vanilla JS function, what relevance does React/Testing Library have? Give a minimal reproducible example of your test. Commented Aug 5, 2022 at 15:56

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.