eligrey / eligrey/FileSaver.js
Using Mocha to test file download using file-saver in a react project, gives "ReferenceError: HTMLAnchorElement is not defined" error
- Dominant language
- JavaScript
- Stars
- 22k
- Forks
- 4.3k
- PR merge metrics
- No merged PRs in 30d
Description
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 :
```js
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 :
```js
describe('', () => {
let wrapper, props;
beforeEach(() => {
props = {
...defaultProps,
handleOnClick: expect.createSpy(),
downloadFile: expect.createSpy().andReturn(() => {})
};
wrapper = shallow();
});
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. (/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.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.