使用 React 测试库的 ReactJS 测试中的 Typescript 错误

Typescript error in ReactJS tests with 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 代码显示 fireEvent.click(button) 行中的错误:Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'.。我怎样才能避免它?我知道我可以像这样进行类型转换:

fireEvent.click(button as Element);

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

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

Typescript 可以在源文件中的任何位置推断出您的变量类型,您需要 'cast' 按钮 HTMLElement 而不是 HTMLElement | null 通过检查它是否不是 null

// button may be null
const button = component.getByText('Locations').parentElement;

if (button) {
  // at this point, typescript knows that button cannot be null
  // so it has HTMLElement type in the block
  fireEvent.click(button);
}

另请注意,我没有将 fireEvent.click() 包裹在 act() 内。因为react-testing-library已经帮你完成了所以这里就没有必要了

如果你想要的是简洁并且你绝对确定元素存在否则测试将失败,你可以通过添加 non-null 断言运算符[=14= 来确保打字稿] 像这样

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

fireEvent.click(button);