bkDev
bkDev

Reputation: 21

How to test onKeyPress function call - React Testing Library

How would I be able to test the functionality of my onkeypress functionality?

any help would be greatly appreciated!

Component -


    import React, { useState } from 'react';

    function Search({ setWeather }) {
      const [city, setCity] = useState('');

      async function getWeather(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          e.target.blur();
          console.log('in here');
          try {
            const key = process.env.REACT_APP_API_KEY;
            const uri = `APIURIHERE`;
            const response = await fetch(uri);
            const responseJson = await response.json();
            setWeather(responseJson);
            setCity('');
          } catch (error) {
            console.log('api error', error);
          }
        }
      }

      return (
        <div>
          <label htmlFor='search-box'>
            <input
              data-testid='location-input'
              id='search-box'
              type='text'
              placeholder='search city'
              value={city}
              onChange={(e) => setCity(e.target.value)}
              onKeyPress={(e) => getWeather(e)}
            />
          </label>
        </div>
      );
    }

    export default Search;

Test -


    import React from 'react';
    import { render, cleanup, fireEvent } from '@testing-library/react';
    import Search from '../Search';

    afterEach(cleanup);
    const mock = jest.fn();

    describe('<Search/>', () => {
      test('onkeypress - function runs', () => {
        const { getByTestId } = render(<Search setWeather={mock} />);
        const inputNode = getByTestId('location-input');
        fireEvent.change(inputNode, { target: { value: 'city_here' } });
        expect(inputNode.value).toBe('city_here');
        fireEvent.keyPress(inputNode, { key: 'Enter', keyCode: 13 });
        // how to test function onkeypress was called inputbox?
        // and how to test what it was it called with?
      });
    });

Upvotes: 2

Views: 10133

Answers (1)

Antonio Dangond
Antonio Dangond

Reputation: 149

According to this Github issue, a charCode param needs to be included with the keyPress method call: fireEvent.keyPress(inputNode, { key: 'Enter', charCode: 13 });

Upvotes: 7

Related Questions