Jest mocking non-default child component in Typescript returns an error

Viewed 425

When using Jest to mock a child component and using Typescript, the test returns an error.

To Reproduce

Steps to reproduce the behavior:
Create a child component:

export const MyChildComponent = () => {
  return (
    <>
      <span>Something there.</span>
    </>
  );
};

then use it in a parent component

import { MyChildComponent } from './components/MyChildComponent';

export const ParentComponent = () => {
  return (
    <>
      <span>Something here.</span>
      <MyChildComponent />
    </>
  );
};

then write a test:

jest.mock('./components/MyChildComponent', () => () => 'mocked');
describe('My parent component', () => {
  it('renders main span', () => {
    render(<ParentComponent>);
  };
};

This returns an errot:

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Expected behavior

The test should not return an error and pass/fail based on test implementation.

This is related to https://github.com/facebook/jest/issues/2984 which was closed 3 days ago and that might be resolved.

1 Answers

So I found out that the issue is that my child component is not exported as default. And given my tsconfig.js (created via the create-react-app bootstrapper), I had to change how I export my child component:

const MyChildComponent = () => {
  return (
    <>
      <span>Something there.</span>
    </>
  );
};
export default MyChildComponent;

and remove the {} in the import when using it.

Related