【问题标题】:Property 'value' does not exist on type 'HTMLElement' in React Testing LibraryReact 测试库中的“HTMLElement”类型上不存在属性“值”
【发布时间】:2020-05-16 02:45:18
【问题描述】:
我正在使用 React-testing-library 并在最后一行出现错误:
期望 (title.value).toBe("testtitle");})}) 。错误消息是“HTMLElement”类型上不存在属性“值”。如何纠正此错误消息以有效地编写此代码?
测试文件
<Router history={history}>
<Route render={(props) =>
<NewQuestion {...props} onSave={jest.fn()}/>}/>
</Router>)
const title= getByPlaceholderText("What's your question? Be specific");
fireEvent.change(title, {target: {value: "testtitle"}})
expect (title.value).toBe("testtitle");})})
【问题讨论】:
标签:
reactjs
typescript
unit-testing
react-testing-library
【解决方案1】:
您应该将title 变量转换为HTMLInputElement 才能真正拥有value 属性。试试下面的代码:
const title = getByPlaceholderText("test") as HTMLInputElement;
【解决方案2】:
铸造的替代方法是使用instanceof narrowing:
const title = getByPlaceholderText("test");
if (!(title instanceof HTMLInputElement)) {
throw new AssertionError("expected title to be an HTMLInputElement");
}
// Now TypeScript knows title is an HTMLInputElement if we made it here.
expect(title.value).toBe("foo");
这比强制转换代码更多,但可以说是更好的测试,因为如果返回的元素不是HTMLInputElement,我们将得到显式失败。这种方法的灵感来自dom-testing-library github issue comment。
如果您必须在多个地点进行此类检查,您可以创建assertion function 以供重复使用:
function assertIsHTMLInputElement(
val: unknown
): asserts val is HTMLInputElement {
if (!(val instanceof HTMLInputElement)) {
throw new AssertionError(`expected ${val} to be an HTMLInputElement`);
}
}