首页 > 解决方案 > Jest mocking non-default child component in Typescript returns an error

问题描述

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.

标签: reactjsts-jest

解决方案


所以我发现问题是我的子组件没有导出为default. 鉴于我的tsconfig.js(通过 create-react-app 引导程序创建),我必须更改导出子组件的方式:

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

并在使用时删除{}导入中的。


推荐阅读