How to mock ResizeObserver to work in unit tests using react testing library

    1. global.ResizeObserver = require('resize-observer-polyfill')
    1. class ResizeObserver {
    2. observe() {
    3. // do nothing
    4. }
    5. unobserve() {
    6. // do nothing
    7. }
    8. disconnect() {
    9. // do nothing
    10. }
    11. }
    12. window.ResizeObserver = ResizeObserver;
    13. export default ResizeObserver;

    https://stackoverflow.com/questions/68679993/referenceerror-resizeobserver-is-not-defined

    1. window.ResizeObserver =
    2. window.ResizeObserver ||
    3. jest.fn().mockImplementation(() => ({
    4. disconnect: jest.fn(),
    5. observe: jest.fn(),
    6. unobserve: jest.fn(),
    7. }));
    8. describe('', () => {
    9. // test ...
    10. });

    “ResizeObserver is not defined” error when running Jest · Issue #40 · ZeeCoder/use-resize-observer

    https://stackoverflow.com/questions/69097709/how-can-i-trigger-resizeobserver-from-a-jasmine-test

    https://stackoverflow.com/questions/55881621/how-to-test-components-resize-behaviour

    1. import ResizeObserver from 'resize-observer-polyfill';
    2. const fn = jest.fn();
    3. const element = document.createElement('div');
    4. document.body.appendChild(element);
    5. new ResizeObserver(() => {
    6. fn();
    7. }).observe(element);
    1. it('should call the fn function', () => {
    2. element.style.width = '100px';
    3. element.style.height = '200px';
    4. expect(fn).toHaveBeenCalledTimes(2);
    5. });

    Why would you want to test that, isn’t it the job for the resize-observer-polyfill maintainers to do so?

    1. <script src="https://rawgit.com/que-etc/resize-observer-polyfill/master/dist/ResizeObserver.js"></script>
    2. <div class="container"></div>
    3. <button onclick="resizeSize()">123</button>
    1. const el = document.createElement('div')
    2. el.style.width = '50px'
    3. el.style.height = '50px'
    4. el.style.background = '#000'
    5. // document.body.appendChild(el)
    6. const ro = new ResizeObserver((_entries) => {
    7. console.warn('大小改变', _entries[0].contentRect)
    8. })
    9. ro.observe(el)
    10. el.style.width = '100px'
    11. el.style.height = '100px'
    12. function resizeSize(){
    13. console.warn(1223)
    14. el.style.width = '500px'
    15. el.style.height = '500px'
    16. }

    目前看起来下面的好像不需要

    1. const ResizeObserver = vi.fn(() => ({
    2. observe: vi.fn(),
    3. unobserve: vi.fn(),
    4. disconnect: vi.fn(),
    5. }))
    6. // https://cn.vitest.dev/guide/mocking.html#%E5%85%A8%E5%B1%80-globals
    7. vi.stubGlobal('ResizeObserver', ResizeObserver)