如何在动态创建脚本标记的自定义钩子中测试 useEffect

时间:2021-05-27 01:11:04

标签: reactjs react-testing-library

我有一个名为 useScript 的自定义钩子: import { useEffect } from 'react';

const useScript = scriptUrl => {
  useEffect(() => {
    const script = document.createElement('script');
    script.src = scriptUrl;
    script.async = true;
    document.body.appendChild(script);
    return () => document.body.removeChild(script);
  }, [scriptUrl]);
};

导出默认使用脚本;

我想测试一下。我是这样装的:

import React from "react";
  import { renderHook } from "@testing-library/react-hooks";
  import useScript from ".";
  
  describe("useScript tests", () => {
      it('verify that the script tag is created', () => {
          const wrapper = ({children}) => <body>{children}</body>;
          const initialProps = {
              scriptUrl: 'https://crm.zoho.com/crm/javascript/zcga.js'
          };
  
          const { result } = renderHook(
              () => useScript('https://crm.zoho.com/crm/javascript/zcga.js'),
              {
                  initialProps,
                  wrapper
              },
          );
      });
  });

我不知道我是否走对了

1 个答案:

答案 0 :(得分:0)

这样:

import React from "react";
import useScript from ".";
import { render, } from '@testing-library/react';

describe("useScript tests", () => {
  it('verify that the script tag is created', () => {
    const scriptUrl = 'https://crm.zoho.com/crm/javascript/zcga.js';

    const WrapperComponent = () => {
      useScript(scriptUrl);
      return null;
    };
      
    render(<WrapperComponent /> );

    const script = document.body.querySelector(`script[src="${scriptUrl}"]`);
    expect(script.src).toBe(scriptUrl);
  });
});
相关问题