我有一个名为useScript的自定义钩子:从"react"导入{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
},
);
});
});
我不知道我是否走对了
这种方式:
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);
});
});