如何使用测试库测试下一个/脚本?

Las*_*zlo 6 reactjs next.js react-testing-library testing-library

我的 React 组件<script>使用 nextJS 渲染标签Head。当尝试使用测试库的方法查询元素时getByTestId,我收到以下消息:

TestingLibraryElementError: Unable to find an element by: [data-testid="keen-to-test"]
Ignored nodes: comments, <script />, <style />
Run Code Online (Sandbox Code Playgroud)

有没有办法包含script在输出中,或者我应该使用不同的策略来验证我的脚本是否已注入?提前致谢

成分

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;
}
Run Code Online (Sandbox Code Playgroud)

测试

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');
  });
Run Code Online (Sandbox Code Playgroud)

Luk*_*ord 0

一种方法是测试 的状态document。例如:

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');
});
Run Code Online (Sandbox Code Playgroud)