Javascript 如何测试onKeyPress函数调用-反应测试库
我怎样才能测试onkeypress功能的功能Javascript 如何测试onKeyPress函数调用-反应测试库,javascript,reactjs,testing,react-testing-library,onkeypress,Javascript,Reactjs,Testing,React Testing Library,Onkeypress,我怎样才能测试onkeypress功能的功能 元素中插入了当前的onkeypress功能 试图测试如何在键盘上测试功能被称为输入框 如何测试它被称为什么 jest、react测试库和react 任何帮助都将不胜感激 组成部分- import React, { useState } from 'react'; function Search({ setWeather }) { const [city, setCity] = useState('');
- 元素中插入了当前的onkeypress功能
- 试图测试如何在键盘上测试功能被称为输入框
- 如何测试它被称为什么
- jest、react测试库和react
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;
从“React”导入React,{useState};
函数搜索({setWeather}){
const[city,setCity]=useState(“”);
异步函数getWeather(e){
如果(e.key=='Enter'){
e、 预防默认值();
e、 target.blur();
console.log('in here');
试一试{
const key=process.env.REACT\u APP\u API\u key;
常量uri=`APIURIHERE`;
常量响应=等待获取(uri);
const responseJson=wait response.json();
setWeather(responseJson);
设定值(“”);
}捕获(错误){
日志('api错误',错误);
}
}
}
返回(
设置城市(即目标值)}
onKeyPress={(e)=>getWeather(e)}
/>
);
}
导出默认搜索;
试验-
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?
});
});
从“React”导入React;
从'@testing library/react'导入{render,cleanup,firevent};
从“../Search”导入搜索;
每次之后(清理);
const mock=jest.fn();
描述(“”,()=>{
测试('onkeypress-函数运行',()=>{
const{getByTestId}=render();
const inputNode=getByTestId('location-input');
change(inputNode,{target:{value:'city_here'}});
expect(inputNode.value).toBe('city_here');
keyPress(inputNode,{key:'Enter',keyCode:13});
//如何测试函数onkeypress被称为inputbox?
//如何测试它被称为什么?
});
});
根据,一个charCode
参数需要包含在keyPress
方法调用中:firevent.keyPress(inputNode,{key:'Enter',charCode:13})代码>为了避免混淆,您是否表示fireEvent.keyPress
不工作,或者您正在试图确定是否调用了setWeather
?