reactjs - 使用 React 测试库进行 ReactJS 测试时出现 Typescript 错误

标签 reactjs typescript react-testing-library

我正在使用 ReactJS、Material UI 和 Typescript。我想测试我的菜单 - 在单击带有标签 Location 的按钮后应该显示。新菜单应包含 Location 1 项。

describe('<LocationsMenu />', () => {
    let component: RenderResult;

    beforeEach(() => {
        component = render(<LocationsMenu />);
    });

    it('should show and hide on click on top item trigger', async () => {
        const button = component.getByText('Locations').parentElement;
        await act(async () => {
            fireEvent.click(button);
        });
        expect(component.getByText('Location 1')).toBeDefined();
    });
});

这有效 - 测试通过。

Visual Studio Code 在 fireEvent.click(button) 行中显示错误: Argument of type 'HTMLElement | null' 不可分配给类型为 'Element | 的参数节点|文件|窗口'.。我怎样才能避免它?我知道我可以进行类型转换,例如:

fireEvent.click(button as Element);

const button = component.getByText('Locations').parentElement as Element;

但也许有更好的解决方案。

最佳答案

如果您想要简洁,并且您绝对确定该元素存在,否则测试会失败,您可以通过添加一个非空断言运算符来确保 typescript ,如下所示

// button may be null, but you say it's not
const button = component.getByText('Locations').parentElement!;

fireEvent.click(button);

关于reactjs - 使用 React 测试库进行 ReactJS 测试时出现 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64418226/

相关文章:

javascript - react JS : onPaste not working as expected

javascript - Typescript + Jquery Ajax + 这个

angular - 如何找出组件或服务依赖于哪些模块?

reactjs - 如何使用 React 测试库测试 `contenteditable` 事件

javascript - react 获取('http://localhost:3000/profile/:id')

javascript - 将缓冲区输入的音频从 48000 下采样到 16000

javascript - Event.target.value 未正确检索值

具有多个模块的 Angular 2 项目结构

css - React 测试库 (RTL) : test a responsive design

reactjs - 如何在 react 测试库中模拟视频持续时间?