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


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


import { useEffect } from 'react';

export const useExampleHook = () => {

  useEffect(() => {

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

    script.src =
    script.async = true;

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

  }, []);
/*test file*/

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

import React from 'react';

import { useExampleHook } from '.';

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

render(<Component />);

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