Testing onload of a script tag with jest and react testing library

Hi,

I’m trying to test that an element added to the DOM by the onload of a script gets rendered. For some reason the test is failing. Please does anyone know if i’m missing something?

  1. The script’s source (src) is an external library/CDN
  2. The script is added to the DOM dynamically in a react hook
  3. The script’s onload calls a function e.g. functionWhichAddsHTMLtoDOM which then renders HTML to the DOM

More details below

/*hook*/

import { useEffect } from 'react';

export const useExampleHook = () => {

  useEffect(() => {

    const script = document.createElement('script');

    script.src =
      'https://xxxxxxx';
    script.async = true;

    script.onload = () => {
       functionWhichAddsHTMLtoDOM() 
/*adds a button with the text i am a button to the DOM*/
    };

    document.body.appendChild(script);
  }, []);
};
/*test file*/

import { render, screen } from '@testing-library/react';

import React from 'react';

import { useExampleHook } from '.';

test('correctly renders button', async () => {
  const Component = () => {
   useExampleHook();
    return <div>Testing Testing</div>;
  };

render(<Component />);


const functionWhichAddsHTMLtoDOM = jest.fn()
expect(functionWhichAddsHTMLtoDOM).toHaveBeenCalledTimes(1)
const button = await screen.getAllByText(/I am a button/i);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.