我如何才能测试我的 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?
});
});
charCode
参数需要包含在 keyPress
方法调用中: fireEvent.keyPress(inputNode, { key: 'Enter', charCode: 13 });
使用 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
函数。
确保您已安装
@testing-library/react
和 @testing-library/jest-dom
。
npm install @testing-library/react @testing-library/jest-dom
以下是如何使用 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!');
});
模拟函数:
jest.fn()
创建一个我们可以跟踪的模拟函数。
渲染组件:我们渲染
KeyPressComponent
,将模拟函数作为道具传递。
获取输入元素:我们使用
getByPlaceholderText
来查找输入字段。
模拟输入更改:
fireEvent.change
模拟在输入字段中键入内容。
模拟按键:
fireEvent.keyPress
模拟按下 Enter 键。
断言:最后,我们检查
handleKeyPress
函数是否使用预期参数调用。