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

Dan*_*age 4 unit-testing typescript reactjs jestjs

我正在使用 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;

Run Code Online (Sandbox Code Playgroud)

这是我到目前为止的测试:

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
    })

});

Run Code Online (Sandbox Code Playgroud)

我收到一个 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 教程,但没有看到任何人遇到与我所看到的类似的错误。

Ade*_*ear 7

我有这个完全相同的问题,但找不到任何关于它的信息。

我终于发现这是由于我的测试文件被命名为spec.ts而不是spec.tsx。

由于泛型的打字稿定义为 <>,使用 jsx 的测试需要在 tsx 文件中。