Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add and execute scripts react-testing-library and jest

We have custom assets brought in via <script> tags that find html tags and render the component. For example, we have <customABC />. When the page loads the scripts find <customABC /> and return what that component should be.

I'm trying to add scripts to my document via the following, before calling render.

  describe('DisclaimerContainer render tests', () => {
  test('simple Disclaimer renders disclaimer content', () => {

    const moduleScript = document.createElement('script');
    moduleScript.src = "https://www.example.com/assets/foo/bar/5.7.0/components.js";
    moduleScript.type = "module";
    moduleScript.async = true;
    document.body.appendChild(moduleScript); //I've also tried document.head.appendChild(moduleScript);
    const {debug} = render(<ContextDisclaimerContainer history={history}/>);
    debug();
  });

Debug() is still showing <customABC /> and not the html it should show.

When you do not have an npm package, and need to include custom scripts, how do you configure these to run in your react-testing-library jest test?

like image 942
Jerm Avatar asked Sep 14 '25 19:09

Jerm


1 Answers

I had success loading a script by customizing the JSDOM in a jest setup file:

// jest.config.js
module.exports = {
  setupFilesAfterEnv: [
    './jest-setup.js',
  ],
};


// jest-setup.js
import { JSDOM } from 'jsdom';
    
const dom = new JSDOM(<!DOCTYPE html><body></body>, {
  resources: 'usable',
  runScripts: 'dangerously',
});

global.window = dom.window;
global.document = dom.window.document;

The key is to configure JSDOM with { resources: 'usable', runScripts: 'dangerously' }. See the jsdom documentation on executing scripts.

like image 193
Leila Hadj-Chikh Avatar answered Sep 17 '25 08:09

Leila Hadj-Chikh