最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test onKeyPress function call - React Testing Library - Stack Overflow

programmeradmin2浏览0评论

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

  • current onkeypress function is inserted in element.

  • Trying to test how to test function onkeypress was called input box?

  • How to test what it was it called with?

  • jest, react-testing-library, and react

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

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

  • current onkeypress function is inserted in element.

  • Trying to test how to test function onkeypress was called input box?

  • How to test what it was it called with?

  • jest, react-testing-library, and react

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

Share Improve this question asked Jul 4, 2020 at 0:08 bkDevbkDev 211 gold badge1 silver badge3 bronze badges 2
  • 1 In order to avoid confusion, are you indicating that fireEvent.keyPress is not working or are you trying to figure out if setWeather was called? – themanatuf Commented Jul 9, 2020 at 9:55
  • "How to test what it was it called with?" you don't--this is an implementation detail, or if you're referring to the DOM event object, something your test provides as a mock. Instead, test the effect clicking the button has on the user interface. In this case, you would test that the weather was retrieved. But since this is never rendered in this ponent, it can't be tested. You'd probably want to test wherever ponent controls the weather state. As far as city goes, you can test that clicking the button clears it out. – ggorlen Commented Nov 6, 2022 at 3:10
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布评论

评论列表(0)

  1. 暂无评论