问题
I am using react testing library to create my test.
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;
My test:
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('')
})
});
The tests now are passed, but why? I just crated an input with type: number, not text, so i expect the test not to be passed? How to check an input with type number?
回答1:
It's because of the Web API. React works with Web API under the hood, and react-testing-library
runs tests using the Web API.
expect(h1).toHaveTextContent('123')
checks the h1
's textContent
property, which is a string
.
It's same for input
's value
property. HTMLInputElement's value
property is always a string
. I'm not 100% sure why it's like that, but it makes sense to me that HTMLInputElement.value
is always a string
regardless of type
.
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.
};
If you really want a number
, HTMLInputElement
has another property called valueAsNumber
, which is a number.
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
By the way, one of the guiding principles of the Testing Library is:
It should be generally useful for testing the application components in the way the user would use it.
Users see numbers on a screen as texts and don't care their "type"s. So, it makes sense that we write tests based on texts that users see. For example, you may want to test if a number is beautifully formatted as well, like 1,234,567
instead of 1234567
, for some applications.
来源:https://stackoverflow.com/questions/64951487/react-test-if-input-accepts-just-number