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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With