Skip to content

Type mismatch in test assertion

Quick summary

Your assertion compares values of different types — the matcher cannot compare a string with a number, for example.

Why this happens

  • The actual value is a different type than expected due to a bug in the code under test

  • The expected value in the assertion is the wrong type (e.g., string vs number)

  • A mock returns a different type than the real function, causing a type mismatch

Minimal example

✗ Broken code
test('gets user age', () => {
  const age = getUserAge(1); // returns '25' (string) due to a bug
  expect(age).toBe(25); // fails — '25' !== 25
});
✓ Fixed code
test('gets user age', () => {
  const age = getUserAge(1); // returns 25 (number) after fix
  expect(age).toBe(25);
});

Fixing the code to return a number instead of a string makes the types match and the assertion pass.

How to diagnose

  • Log the actual value and its type to compare with the expected value

  • Check the function signature and return type of the code under test

  • Verify that mocks return the same type as the real implementation

How to fix

  • Fix the code under test to return the correct type

  • Correct the expected value in the assertion to match the actual type

  • Update the mock to return the same type as the real function

How to prevent

  • Use TypeScript with strict types to catch type mismatches at compile time

  • Ensure mocks are typed to match the real implementation's return type

Related Resources

Related Glossary

Related Lessons

← Back to language