reactjs - Jest 错误 - 未实现 : navigation (except hash changes) when click event is triggered on an anchor element

标签 reactjs unit-testing jestjs react-testing-library

我已经使用 jest 版本编写了单元测试 26.0.0带有反应测试库和节点版本 14.2.0 .下面是我的 React 功能组件,它有一个按钮,点击后会调用 ajax 来下载报告文件。

const ReportListTable = () => {
    const { downloadReports } = useReports();

    const onClickDownload = () => {
        let fileName = `Report.zip`;
        downloadReports()
            .then((response) => response.arrayBuffer())
            .then((data) => {
                const blob = new Blob([data], { type: "octet/stream", endings: "native" });
                const url = window.URL.createObjectURL(blob);
                const anchor = document.createElement("a");
                anchor.setAttribute("href", url);
                anchor.setAttribute("download", fileName);
                anchor.click();
                window.URL.revokeObjectURL(url);
            })
            .catch((error?: Error | Response) => {
                if (error instanceof Error) {
                    message.error(error?.message);
                }
            });
    };

    return (
        <div>
            <Button data-testid="download-btn" onClick={onClickDownload}>
                Download
            </Button>
        </div>
    );
};
我有以下测试套件,其中 createObjectURLrevokeObjectURL在测试运行之前。
describe("Test Reports List Table component", () => {
    const { URL } = window;

    beforeAll(() => {
        window.URL.createObjectURL = jest.fn();
        window.URL.revokeObjectURL = jest.fn();

        jest.spyOn(useReportsHook, "useReports").mockReturnValue(useReportsMockValue);
    });

    afterAll(() => {
        window.URL = URL;
        jest.clearAllMocks();
    });

    it("should handle row button enabled and download on button clicked", async () => {
        jest.spyOn(useReportsContextHook, "useReportsContext").mockReturnValue([{ checkedIds: ["report_1"] }, jest.fn]);
        const { asFragment } = render(<ReportListTable />);
        
        fireEvent.click(await screen.getByTestId(elements.downloadTestId));
        await waitFor(() => expect(window.URL.createObjectURL).toHaveBeenCalled());
        await waitFor(() => expect(window.URL.revokeObjectURL).toHaveBeenCalled());
        expect(asFragment).toMatchSnapshot();
    });
});
测试用例已通过,但会引发以下错误。
  console.error
    Error: Not implemented: navigation (except hash changes)
        at module.exports (/Users/user/Documents/lydia-github/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
        at navigateFetch (/Users/user/Documents/lydia-github/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/window/navigation.js:76:3)
        at exports.navigate (/Users/user/Documents/lydia-github/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/window/navigation.js:54:3)
        at Timeout._onTimeout (/Users/user/Documents/lydia-github/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHyperlinkElementUtils-impl.js:81:7)
        at listOnTimeout (internal/timers.js:549:17)
        at processTimers (internal/timers.js:492:7) undefined
我试图 mock location引用此线程后的对象 How to fix Error: Not implemented: navigation (except hash changes) ,但这没有帮助。我需要帮助来解决这个错误。

最佳答案

我已经解决了这个问题:
JSDom 不喜欢你做导航 - 参见,https://github.com/jsdom/jsdom/issues/2112#issuecomment-359297866
我们在这里遇到的问题是代码在 anchor 上执行点击事件:

const anchor = document.createElement("a");
anchor.setAttribute("href", url);
anchor.setAttribute("download", fileName);
anchor.click();
点击一个 anchor 是一个导航,通常,我认为 JSDom 不同意。
解决烦人的日志记录,而不是 mock location , mock click() :
HTMLAnchorElement.prototype.click = jest.fn();
这对我有用。
顺便说一句,我也不得不 mock window.URL.createObjectUrl调用我:
TypeError: window.URL.createObjectURL is not a function
...所以:
global.window.URL.createObjectURL = jest.fn();
希望这对你有用。

关于reactjs - Jest 错误 - 未实现 : navigation (except hash changes) when click event is triggered on an anchor element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65402808/

相关文章:

javascript - 辅助函数reactjs

javascript - 获取 React-select 分组选项的父值

javascript - 为什么每次组件重新渲染时都会运行 useEffect?

unit-testing - Jest 单元测试 : block all outgoing traffic

javascript - '引用错误 : jest is not defined' when running unit test

node.js - 开 Jest - 语法错误 : Cannot use import statement outside a module with @nestjs/axios

javascript - 如果您要查找的元素不存在,如何不破坏 Cypress 测试

c++ - 如何使用 gMock 创建模拟对象?

php - 应该使用哪种技术来测试 PHPUnit 中的抽象类功能?

javascript - enzyme 在浅层测试中找不到子组件