reactjs - 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.
解决方案
所以我发现问题是我的子组件没有导出为default
. 鉴于我的tsconfig.js
(通过 create-react-app 引导程序创建),我必须更改导出子组件的方式:
const MyChildComponent = () => {
return (
<>
<span>Something there.</span>
</>
);
};
export default MyChildComponent;
并在使用时删除{}
导入中的。
推荐阅读
- php - 无法在php中第二次在循环中执行程序
- c++ - 将 C 函数转换为 C++ 语言
- python - Django 显示的日期时间不会根据用户的本地时区而改变
- c# - 空格和正则表达式
- bash - bash脚本,如何检查条件是否为真,它应该检查下5次或下50秒相同的条件,它是真的,警报
- excel - VBA 使用 .click on getelment by id 不断加载
- angular - Angular 8下拉选项默认更新ArrayList后的最后一个新值
- python - 如何用另一个日期替换日期中的日期?
- android - 警告:此平台不支持 ToastAndroid。反应原生错误
- count - Power BI - 将 COUNT 除以 DISTINCTCOUNT