How to test next/script with testing-library?

Viewed 1396

My react component renders a <script> tag using nextJS Head. When trying to query the element with testing-libary's getByTestId method and I get the message below:

TestingLibraryElementError: Unable to find an element by: [data-testid="keen-to-test"]
Ignored nodes: comments, <script />, <style />

Is there a way to include script in the output or should I use a different strategy to verify if my script is injected? thanks in advance

component

import Head from 'next/head';

const FancyScript = ({src}) => {
  if (src) {
   return (
     <Head>
      <script
        data-testid="keen-to-test"
        type="text/javascript"
        async
        src={src}
      </script>
     </Head>
   )
  }
  return null;
}

test

import { render } from '@testing-library/react';
import FancyScript from '/fancy-location';

it('return some fancy', () => {
    const { getByTestId } = render(<FancyScript src="real_src_here" />);
    expect(getByTestId('keen-to-test')).toHaveAttribute('src', 'real_src_here');
  });
1 Answers

One approach is to test the state of the document. For example:

it('Has the correct src', () => {
  // I'm using `next/script` here, but it should also work with `next/head`
  render(<Script src="myScript.js" />);

  expect(document.querySelector('script')).toHaveAttribute('src', 'myscript.js');
});
Related