1

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="leadoo-experiment"]
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');
  });
Laszlo
  • 2,137
  • 17
  • 21
  • First of all, you **can't** use script like this. See https://stackoverflow.com/questions/53805387/render-script-tag-in-react-component and https://stackoverflow.com/questions/34424845/adding-script-tag-to-react-jsx. Your code is incorrect, testing the wrong code is meaningless – slideshowp2 Jul 16 '21 at 02:01
  • good point @slideshowp2, I hid some implementation detail to set a better focus on the question. I'm using nextjs and render the script tag into the head section of my HTML doc. – Laszlo Jul 16 '21 at 11:20
  • You could try mocking `next/head` during your test. – juliomalves Jul 16 '21 at 23:49

0 Answers0