繁体   English   中英

使用 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 Code 在fireEvent.click(button)行中显示错误: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | Node | Document | Window'. 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 可以在源文件中的任何位置推断出您的变量类型,您需要将按钮“强制转换”为HTMLElement而不是HTMLElement | null 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已经为您完成了,所以这里没有必要。

如果您想要简洁并且您绝对确定该元素存在,否则测试将失败,您可以通过添加这样的非空断言运算符来确保打字稿

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

fireEvent.click(button);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM