React test se l'input accetta solo un numero

Nov 22 2020

Sto usando la libreria di test React per creare il mio 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;

Il mio 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('')
    })
});

I test adesso sono passati, ma perché? Ho appena creato un input con tipo: numero, non testo, quindi mi aspetto che il test non venga superato? Come controllare un input con il numero di tipo?

Risposte

3 ShuheiKagawa Nov 22 2020 at 07:44

È a causa dell'API Web. React funziona con l'API Web sotto il cofano ed react-testing-libraryesegue i test utilizzando l'API Web.

expect(h1).toHaveTextContent('123')controlla il h1's textContentdi proprietà, che è una string.

È lo stesso per inputla valueproprietà di. HTMLInputElementLa valueproprietà di è sempre una string. Non sono sicuro al 100% perché sia ​​così, ma per me ha senso che HTMLInputElement.valuesia sempre un a stringprescindere 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.
    };

Se vuoi davvero un number, HTMLInputElementha un'altra proprietà chiamata valueAsNumber, che è un numero.

valueAsNumber

double: restituisce il valore dell'elemento, interpretato come uno dei seguenti, nell'ordine:

  • Un valore temporale
  • Un numero
  • NaN se la conversione è impossibile

A proposito, uno dei principi guida della Testing Library è:

Dovrebbe essere generalmente utile per testare i componenti dell'applicazione nel modo in cui l'utente lo userebbe.

Gli utenti vedono i numeri su uno schermo come testi e non si preoccupano del loro "tipo". Quindi, ha senso che scriviamo test basati su testi che gli utenti vedono. Ad esempio, potresti voler verificare se un numero è ben formattato anche, come 1,234,567invece di 1234567, per alcune applicazioni.