【问题标题】:how to test a useEffect inside custom hook that create a script tag dynamically如何在动态创建脚本标签的自定义钩子中测试 useEffect
【发布时间】:2021-08-15 06:15:49
【问题描述】:

我有一个名为 useScript 的自定义钩子: 从“反应”导入 { useEffect };

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]);
};

导出默认useScript;

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

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
              },
          );
      });
  });

我不知道我是否走对了路

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

    这边:

    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);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-19
      • 2020-01-26
      • 2021-12-26
      • 2020-08-04
      • 2021-02-17
      • 1970-01-01
      • 2020-07-10
      • 2022-10-09
      相关资源
      最近更新 更多