目前在没有 TypeScript 的情况下,这段代码可以正常工作,但不幸的是,现在它无法正常工作。它给了我以下错误:属性“值”在类型“HTMLElement”上不存在。不确定这有什么问题。似乎是在唠叨值(value)。在这种情况下,我使用 Jest 测试和 React。不确定我是否可以忽略此错误或应该修复此错误以避免将来出现奇怪的错误。
import React from 'react';
import axios from 'axios';
import { useDispatch } from "react-redux";
import { getData } from '../../../actions/index';;
export const SearchInput : React.FC = () => {
const dispatch = useDispatch();
let input: any;
const getInputValue = (value: string):void => {
let url = `https://api.tvmaze.com/search/shows?q=${value}`
}
return (
<div className="container">
<h1>Keyword</h1>
<form className="form display-inline-flex"
onSubmit={e => {
e.preventDefault()
if(!input.value.trim()) return;
getInputValue(input.value);
}}>
<input className="form-input-field disable-outline display-inline"
ref={node => (input = node)}
placeholder="Search catalog"
aria-label="search-input"
/>
<button type="submit" className="btn btn-grey white-color display-inline">
Search
</button>
</form>
</div>
)
}
export default SearchInput;
// Jest testing
import React from "react"
import { render, fireEvent } from "@testing-library/react";
import { SearchInput } from "./SearchInput";
import { Provider } from "react-redux";
import { store } from "../../../Store";
const setup = () => {
const utils = render(
<Provider store={store}>
<SearchInput/>
</Provider>);
const input = utils.getByLabelText("search-input");
return {
input,
...utils
}
}
test("It should check if input field get the value passed", () => {
const { input } = setup();
fireEvent.change(input, { target: { value: "search-bar-test" } })
expect(input.value).toBe("search-bar-test")
});
最佳答案
如果你添加一个类型断言,你应该可以开始了:
const input = utils.getByLabelText("search-input") as HTMLInputElement;
关于reactjs - 类型 'value' 上不存在 TypeScript 属性 'HTMLElement'。 react Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62905075/