gpt4 book ai didi

reactjs - Typescript + React 测试库 - 'SidebarItem' 指的是一个值,但在这里被用作类型。你的意思是 'typeof SidebarItem' ?ts(2749)

转载 作者:行者123 更新时间:2023-12-04 11:59:02 25 4
gpt4 key购买 nike

我正在使用 Jest + RTL 为一个简单的 React 组件创建一个测试。
这是我的组件:

import React from 'react';

import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Grid from '@material-ui/core/Grid';

import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles((theme) => ({
centeredContent: {
justifyContent: 'center',
},
text: {
paddingLeft: theme.spacing(5),
},
spacer: {
paddingLeft: theme.spacing(5),
},
}));

interface SidebarItemProps {
children: any; //TODO - find an extensible type that we can use for {children}
text?: string;
openSidebar: boolean;
}

const SidebarItem: React.FC<SidebarItemProps> = ({ children, text, openSidebar }) => {
const classes = useStyles();
return (
<ListItem button className={classes.centeredContent}>
{!openSidebar && <Grid className={classes.spacer} />}
<ListItemIcon>{children}</ListItemIcon>
<ListItemText className={classes.text} primary={text} primaryTypographyProps={{ variant: 'body1' }} />
</ListItem>
);
};

export default SidebarItem;

这是我到目前为止的测试:
import React from 'react';

import '@testing-library/jest-dom/extend-expect';
import { render, screen, RenderResult } from '@testing-library/react';
import SidebarItem from '../SidebarItem';

describe('SidebarItem', () => {
// afterEach(() => {
// jest.clearAllMocks();
// });

// afterAll(() => {
// jest.restoreAllMocks();
// });

let documentBody: RenderResult;

beforeEach(()=> {
documentBody = render(<SidebarItem/>) // I get an error here
})

});

我收到一个 TS 错误: 'SidebarItem' refers to a value, but is being used as a type here. Did you mean 'typeof SidebarItem'?ts(2749)我最初的猜测是,我使用的 Jest、RTL 或 Typescript 版本都是过时的。我已经更新了 RTL、Jest 和 Typescript。我还将 jest.config.js 设置为 jsdom测试环境。我也在关注网络上的大多数 RTL 教程,但没有看到任何人遇到与我所看到的类似的错误。

最佳答案

我有这个完全相同的问题,但找不到任何关于它的信息。
我终于发现这是由于我的测试文件被命名为spec.ts而不是spec.tsx。
由于泛型的 typescript 定义为 <>,使用 jsx 的测试需要在 tsx 文件中。

关于reactjs - Typescript + React 测试库 - 'SidebarItem' 指的是一个值,但在这里被用作类型。你的意思是 'typeof SidebarItem' ?ts(2749),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com