reactjs - 类型 'value' 上不存在 TypeScript 属性 'HTMLElement'。 react Jest 测试

标签 reactjs typescript testing jestjs

目前在没有 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")
});

ct

最佳答案

如果你添加一个类型断言,你应该可以开始了:

const input = utils.getByLabelText("search-input") as HTMLInputElement;

关于reactjs - 类型 'value' 上不存在 TypeScript 属性 'HTMLElement'。 react Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62905075/

相关文章:

java - TestNG/万无一失 : How to generate an XML report after each test?

javascript - 如何检查 *chunk.js 中的不同源大小

javascript - 在 "Warning: setState(...): Can only update a mounted or mounting component."函数中设置状态时出现 "FB.Event.subscribe()"错误

javascript - Svelte 仅支持 es6+ 语法。将您的 'compilerOptions.target' 设置为 'es6' 或更高

android - 如何在 android 仪器测试中停止和重新启动 Activity ?

java - 这个循环怎么能退出呢?

node.js - react 原生初始化错误

node.js - 我是否必须使用 ngrok 来公开 MERN 堆栈的前端和后端才能使 CRUD 操作正常工作?

typescript - TypeScript 中的父类(super class)型约束

typescript - VS2015 中 TypeScript 的 Mocha 单元测试