如果输入仅接受数字,则反应测试

React test if input accepts just number

我正在使用 React 测试库来创建我的测试。

import React, {useState} from 'react';

const Input = () => {
    const [state, setState] = useState(0);

    const onChange = (e) => {
        setState(e.target.value)
    };

    return (
        <div>
            <h1>{state}</h1>
            <input placeholder='type' type="number" value={state} onChange={onChange}/>
        </div>
    );
};

export default Input;

我的测试:

import Input from "./Input";
import { render, fireEvent } from '@testing-library/react'


describe('test if render', ()=> {
    test('check render text', ()=> {
        const { getByPlaceholderText, getByRole } = render(<Input />);
        const input = getByPlaceholderText('type');
        const h1 = getByRole('heading', {level: 1});
        fireEvent.change(input, { target: { value: "123" } });
        expect(h1).toHaveTextContent('123')
    });
    test('check not render text', ()=> {
        const { getByPlaceholderText, getByRole } = render(<Input />);
        const input = getByPlaceholderText('type');
        const h1 = getByRole('heading', {level: 1});
        fireEvent.change(input, { target: { value: "" } });
        expect(h1).toHaveTextContent('')
    })
});

现在测试通过了,但是为什么呢?我刚刚创建了一个输入类型:数字,而不是文本,所以我希望测试不会通过?如何检查类型编号的输入?

这是因为网络 API。 React 在后台与 Web API 一起工作,react-testing-library 使用 Web API.

运行测试

expect(h1).toHaveTextContent('123') 检查 h1textContent 属性,这是一个 string.

inputvalue 属性 也一样。 HTMLInputElementvalue 属性 始终是 string。我不是 100% 确定为什么会这样,但对我来说 HTMLInputElement.value 始终是 stringtype.

无关
    const onChange = (e) => {
        setState(e.target.value) // e.target.value is already a string. So, the state gets a string instead of a number here.
    };

如果你真的想要一个 numberHTMLInputElement 有另一个 属性 叫做 valueAsNumber,这是一个数字。

valueAsNumber

double: Returns the value of the element, interpreted as one of the following, in order:

  • A time value
  • A number
  • NaN if conversion is impossible

顺便说一下,the guiding principles of the Testing Library 之一是:

It should be generally useful for testing the application components in the way the user would use it.

用户将屏幕上的数字视为文本,并不关心他们的“类型”。因此,我们根据用户看到的文本编写测试是有道理的。例如,您可能想测试一个数字的格式是否也很漂亮,例如 1,234,567 而不是 1234567,对于某些应用程序。