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