Skip to content

Using Mocha to test file download using file-saver in a react project, gives "ReferenceError: HTMLAnchorElement is not defined" error #671

Open
@roshmani

Description

@roshmani

I am trying to test the file-download on click of a button in a react project, which uses 'saveAs' from npm file-saver
The function for downloading is as follows :

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

A button component uses this function which is passed as prop to it and is called 'onClick'.
The test is as follows :

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

On running the test it gives

ReferenceError: HTMLAnchorElement is not defined    
    at /node_modules/file-saver/src/FileSaver.js:75:19
    at /node_modules/file-saver/dist/FileSaver.min.js:1:106
    at Object.<anonymous> (/node_modules/file-saver/dist/FileSaver.min.js:1:154)......

error and test fails. The file download seem to work though.

what can be done to get it working ? Please help. If i use the 'saveAs' from here https://www.npmjs.com/package/save-as it works just fine in the tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions