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

2.4K
Views
Cómo simular ResizeObserver para trabajar en pruebas unitarias usando la biblioteca de pruebas de reacción

Si alguien puede ayudar, tengo un gancho personalizado que usa ResizeObserver para cambiar el ancho de un componente. Mi problema es que cuando voy a ejecutar mi prueba de unidades, rompe todas mis pruebas y al mirar la instantánea no muestra todos los elementos en el dom. Estaba funcionando antes hasta que implementé el ResizeObserver. ¿Alguien sabe si hay alguna manera de burlarme del ResizeObserver para que no esté indefinido? U otras sugerencias.

 import * as React from 'react'; import ResizeObserver from 'resize-observer-polyfill'; const useResizeObserver = (ref: { current: any }) => { const [dimensions, setDimensions] = React.useState<DOMRectReadOnly>(); React.useEffect(() => { const observeTarget = ref.current; const resizeObserver = new ResizeObserver((entries) => { entries.forEach((entry) => { setDimensions(entry.contentRect); }); }); resizeObserver.observe(observeTarget); return () => { resizeObserver.unobserve(observeTarget); }; }, [ref]); return dimensions; }; export default useResizeObserver; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import mockFetchProfileActivity from '../../../services/mocks/fetch-profile-activity'; import BarChart from './BarChart'; const component = <BarChart userActivity={mockFetchProfileActivity} />; describe('Render barElement Chart component', () => { const observers: any[] = []; let resizeHandler: (observers: any[]) => void; (window as any).ResizeObserver = (e: any) => { resizeHandler = e; return { observe(element: any) { observers.push(element); }, unobserve(element: any) { const i = observers.indexOf(element); if (i !== -1) { observers.splice(i, 1); } } }; }; it('Matches the snapshot', () => { // resizeHandler(observers); const container = render(component); expect(container).toMatchSnapshot(); }); it('when clicking on a chart barElement drilldown "challenges" are shown', async () => { // arrange const componentRender = render(component); waitFor(() => resizeHandler(observers)); // act const barElement = componentRender.container.querySelector('svg rect'); if (barElement) userEvent.click(barElement); // assert expect(screen.getByText('Challenge 1')).toBeInTheDocument(); }); });
over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

Simular el ResizeObserver:

 class ResizeObserver { observe() { // do nothing } unobserve() { // do nothing } disconnect() { // do nothing } } window.ResizeObserver = ResizeObserver; export default ResizeObserver;

muestra.prueba.js

 import ResizeObserver from './__mocks__/ResizeObserver'; import module from 'sample'; describe('module', ()=> { it('returns an instance of ResizeObserver', () => { // do something that uses the resize observer // NOTE: The actual observe handler would not be called in jsdom anyway as no resize would be triggered. // eg expect(module.somethingThatReturnAReference to the resize observer).toBeInstanceOf(ResizeObserver); }); });

fuente

over 4 years ago · Santiago Trujillo Report

0

Tuve un problema similar al usar la configuración de la aplicación Create React.

Si ese es tu caso, puedes crear un archivo en tu directorio raíz llamado setupTest.js y agregar el siguiente código:

 import '@testing-library/jest-dom/extend-expect'; import 'jest-extended'; jest.mock('./hooks/useResizeObserver', () => () => ({ __esModule: true, default: jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })), }));

Puede encontrar más información para configurar el entorno de prueba para Create React App aquí y la API ResizeObserver aquí

over 4 years ago · Santiago Trujillo Report

0

Elegí agregar el polyfill como una dependencia de desarrollo y agregar la siguiente línea a setupTests.js/ts:

 global.ResizeObserver = require('resize-observer-polyfill')
over 4 years ago · Santiago Trujillo Report

0

He agregado a setupTests.js/ts el siguiente código:

 global.ResizeObserver = jest.fn().mockImplementation(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), }))
over 4 years ago · Santiago Trujillo 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!