【问题标题】:Using Mocha to test file download using file-saver in a react project, gives "ReferenceError: HTMLAnchorElement is not defined" error使用 Mocha 在 React 项目中使用文件保护程序测试文件下载,给出“ReferenceError: HTMLAnchorElement is not defined”错误
【发布时间】:2020-12-01 06:42:01
【问题描述】:

我正在尝试通过单击反应项目中的按钮来测试文件下载,该项目使用 npm 文件保护程序中的“saveAs”https://www.npmjs.com/package/file-saver

下载功能如下:

const downloadFile = (csvData) => {
    const dataFile = new Blob([csvData], {
        type: 'text/csv;charset=utf-8;'
    });
    saveAs(
        dataFile,
        `filename.csv`
    );
};

按钮组件使用此函数,该函数作为道具传递给它,称为“onClick”。 测试如下:


describe('<ExportButton/>', () => {
    let wrapper, props;

    beforeEach(() => {
        props = {
            ...defaultProps,
            handleOnClick: expect.createSpy(),
            downloadFile: expect.createSpy().andReturn(() => {})
        };

        wrapper = shallow(<ExportButton {...props} />);
    });

    afterEach(() => {
        expect.restoreSpies();
    });

   
    it('should call the downloadFile and save the file in location specified', (done) => {
        wrapper.find('Button').simulate('click');
        setTimeout(() => {
            expect(props.downloadFile).toHaveBeenCalled();
            done();
        }, 50);
    });
});

在运行它给出的测试时

ReferenceError: HTMLAnchorElement 未定义
在 /node_modules/file-saver/src/FileSaver.js:75:19 在 /node_modules/file-saver/dist/FileSaver.min.js:1:106 在对象。 (/node_modules/file-saver/dist/FileSaver.min.js:1:154)......

错误和测试失败。

谁能告诉我如何解决这个问题

提前致谢

【问题讨论】:

    标签: reactjs unit-testing mocha.js enzyme filesaver.js


    【解决方案1】:

    在您的测试设置文件中,尝试设置:

    global.HTMLAnchorElement = window.HTMLAnchorElement;
    

    【讨论】:

    • 我已经通过添加解决了它:global.HTMLElement = window.HTMLElement; global.HTMLAnchorElement = window.HTMLAnchorElement;在设置文件中,感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 2021-04-16
    相关资源
    最近更新 更多