Sunday, 9 May 2021

test document.body.appendChild being called in useScript React hook (Jest / Enzyme)

I am writing unit tests in Jest for this useScript hook: https://usehooks.com/useScript/

My project uses Jest / Enzyme for testing (we don't use React Testing Library)

I am trying to test that document.body.appendChild has been called but when I run the tests I get this response from Jest:

Expected: ObjectContaining {"src": "https://ift.tt/3tgfnpL", "type": "text/javascript"} Number of calls: 0

Simplified version of the useHook script:

export const useScript = (src) => {
      const [status, setStatus] = useState(src ? 'loading' : 'idle');
      useEffect(
        () => {
          if (!src) {
            setStatus('idle');
            return;
          }
          let script = document.querySelector(`script[src="${src}"]`);
          if (!script) {
            script = document.createElement('script');
            console.log(`document: ${document}`);
            script.src = src;
            script.async = true;
            script.setAttribute('data-status', 'loading');
            document.body.appendChild(script);
          }
        },
        [src] 
      );
      return status;
    };

Jest test:

import { useEffect, useState } from 'react';
import { useScript } from '../useScript';

const mockSetStatus = jest.fn();

jest.mock('../../../makeScriptDOMElement');
jest.mock('react');

const mockScriptSrc = 'https://code.jquery.com/jquery-3.6.0.slim.min.js';

describe('useScript', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });
  
   it('should append the script to the document body', async () => {
    useState.mockReturnValueOnce(['loading', mockSetStatus]);
    useScript(mockScriptSrc);
    const [effect] = useEffect.mock.calls[0];
    await effect();

    jest.spyOn(document.body, 'appendChild');
    expect(document.body.appendChild).toBeCalledWith(
      expect.objectContaining({
        type: 'text/javascript',
        src: mockScriptSrc,
      })
    );
  });
 });


from test document.body.appendChild being called in useScript React hook (Jest / Enzyme)

No comments:

Post a Comment