如何测试 onKeyPress 函数调用 - React 测试库

1 javascript testing onkeypress reactjs react-testing-library

我如何才能测试 onkeypress 功能的功能?

  • 当前的 onkeypress 函数已插入到元素中。

  • 试图测试如何测试onkeypress函数被调用的输入框?

  • 如何测试它的调用方式?

  • 玩笑、反应测试库和反应

任何帮助将不胜感激!

成分 -


    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;

Run Code Online (Sandbox Code Playgroud)

测试 -


    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?
      });
    });

Run Code Online (Sandbox Code Playgroud)

小智 7

根据此 Github 问题,方法调用charCode中需要包含一个参数keyPressfireEvent.keyPress(inputNode, { key: 'Enter', charCode: 13 });