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

问题描述 投票:0回答:2

我如何才能测试我的 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;

测试-


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

javascript reactjs testing react-testing-library onkeypress
2个回答
7
投票

根据 this Github issues

charCode
参数需要包含在
keyPress
方法调用中:
fireEvent.keyPress(inputNode, { key: 'Enter', charCode: 13 });


0
投票

使用 React 测试库在 React 组件中测试

onKeyPress
函数调用涉及模拟按键事件并验证是否调用了正确的函数。这是带有示例的分步指南。

示例组件

假设您有一个简单的输入组件,按下键时会调用一个函数。

import React, { useState } from 'react';

const KeyPressComponent = ({ onKeyPress }) => {
    const [value, setValue] = useState('');

    const handleKeyPress = (event) => {
        if (event.key === 'Enter') {
            onKeyPress(value);
        }
    };

    return (
        <input
            type="text"
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="Type something and press Enter"
        />
    );
};

export default KeyPressComponent;

测试用例

现在,让我们为该组件编写一个测试用例,以确保按下 Enter 键时调用

onKeyPress
函数。

第 1 步:设置您的测试环境

确保您已安装

@testing-library/react
@testing-library/jest-dom

npm install @testing-library/react @testing-library/jest-dom

第 2 步:编写测试

以下是如何使用 React 测试库测试

onKeyPress
函数调用。

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import KeyPressComponent from './KeyPressComponent'; // Adjust the import as needed

test('calls onKeyPress with the input value when Enter is pressed', () => {
    const handleKeyPress = jest.fn(); // Mock function
    const { getByPlaceholderText } = render(<KeyPressComponent onKeyPress={handleKeyPress} />);

    const input = getByPlaceholderText('Type something and press Enter');

    // Type into the input field
    fireEvent.change(input, { target: { value: 'Hello, World!' } });

    // Simulate pressing the Enter key
    fireEvent.keyPress(input, { key: 'Enter', code: 'Enter', charCode: 13 });

    // Assert that the mock function was called with the correct value
    expect(handleKeyPress).toHaveBeenCalledWith('Hello, World!');
});

测试说明

  1. 模拟函数

    jest.fn()
    创建一个我们可以跟踪的模拟函数。

  2. 渲染组件:我们渲染

    KeyPressComponent
    ,将模拟函数作为道具传递。

  3. 获取输入元素:我们使用

    getByPlaceholderText
    来查找输入字段。

  4. 模拟输入更改

    fireEvent.change
    模拟在输入字段中键入内容。

  5. 模拟按键

    fireEvent.keyPress
    模拟按下 Enter 键。

  6. 断言:最后,我们检查

    handleKeyPress
    函数是否使用预期参数调用。

© www.soinside.com 2019 - 2024. All rights reserved.