简体   繁体   中英

How to test dynamic changes to the DOM via JavaScript with Jest or some other testing library?

I am dynamically adding a <script> tag to the document <head> on page load based on the environment.

The Function:

export const loadScript = () => {
  // load script tag into head
  const HEAD = document.getElementsByTagName('head')
  const SCRIPT_TAG = document.createElement('script')
  SCRIPT_TAG.setAttribute('src', process.env.SCRIPT_SRC)
  SCRIPT_TAG.setAttribute('async', true)
  HEAD[0].append(SCRIPT_TAG)
}

I want to write a test that checks if once the loadScript() function is run that the <script> tag made it into the head. Our environment is set up with Jest, and I haven't found a satisfactory example that demonstrates how to do it, or works.

I am new to testing, and would appreciate any solutions, or hints offered.

I suppose the easiest way to test it would be something like this:

test('loadScript', () => {
  process.env.SCRIPT_SRC = 'the-src';
  loadScript();
  expect(document.head.innerHTML).toBe('<script src="the-src" async="true"></script>');
});

This works because the default test environment for Jest is jsdom which simulates the document .

test('loadScript', () => {
  loadScript();
  const script = document.getElementsByTagName('script')[0];
  // trigger the callback
  script.onreadystatechange(); // or script.onLoad();
  expect("something which you have on load").toBe('expected result on load');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM