Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

400
Views
¿Cómo puedo probar el accesorio `onKeyDown` en React con @testing-library/user-event versión 14?

Estoy creando una lista de elementos de menú usando React. Quiero probar que cuando un usuario hace clic o presiona Intro en un elemento, se llama al accesorio onSelect .

Aquí hay una versión simplificada de mi componente:

 import React from "react"; export const Item = ({ children, onSelect }) => { const onKeyDown = ({ keyCode }) => keyCode === 13 && onSelect(); return ( <div onClick={onSelect} onKeyDown={onKeyDown} tabIndex={0}> {children} </div> ); };

Aquí está mi prueba:

 describe("Item", () => { it("calls onSelect when user clicks on the item or presses Enter", async () => { const user = userEvent.setup() const onSelect = jest.fn(); const children = "Settings"; render(<Item onSelect={onSelect}>{children}</Item>); const item = screen.getByText(children); await user.click(item); expect(onSelect).toHaveBeenCalledTimes(1); await user.pointer({target: item, keys: '[Enter]'}) expect(onSelect).toHaveBeenCalledTimes(2); }); });

Al ejecutar las pruebas obtengo el siguiente resultado:

 Item › calls onSelect when user clicks on the item or presses Enter expect(jest.fn()).toHaveBeenCalledTimes(expected) Expected number of calls: 2 Received number of calls: 1 48 | 49 | await user.pointer({target: item, keys: '[Enter]'}) > 50 | expect(onSelect).toHaveBeenCalledTimes(2); | ^ 51 | }); 52 | }); 53 |

¿Cómo puedo probar que se llamó onSelect cuando el usuario presiona Enter en el componente del elemento?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

https://testing-library.com/docs/user-event/keyboard

La API de keyboard permite simular interacciones con un teclado. Acepta una string que describe las acciones clave.

 await user.keyboard('[Enter]')

KeyboardEvent.keyCode está en desuso.
Por lo tanto, no lo admitimos y lo alentamos a que actualice su implementación para usar funciones no obsoletas como KeyboardEvent.key o KeyboardEvent.code .

https://codesandbox.io/s/crazy-snyder-gurptu?file=/src/Item.test.js

about 4 years ago · Juan Pablo Isaza Report

0

Dela documentación

 fireEvent.keyDown(domNode, {key: 'Enter', code: 'Enter', charCode: 13}) fireEvent.keyDown(domNode, {key: 'A', code: 'KeyA'})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!