I'm stuck trying to mock my method which downloads a csv from the devextreme datagrid. I'm stuck trying to mock this part of the function.
saveAs(new Blob([buffer], { type: 'application/octet-stream' }),
'DataGrid.csv')
I get the error .
(0 , _fileSaver.default) is not a function
How can I mock the saveAs from file-saver in Jest.
Here is my download function and the jest file
const downloadCsv = () => {
const workbook = new Workbook()
const worksheet = workbook.addWorksheet('Main Sheet')
const exportRes = exportDataGrid({
component: state.gridInstance,
worksheet: worksheet
})
exportRes.then(() => {
workbook.csv.writeBuffer().then((buffer) => {
saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.csv')
})
})
}
----------------------------------------------------------------------
import { shallowMount } from '@vue/test-utils'
import downloadComp from '@/components/data-grid/downloadComp'
jest.mock('devextreme/excel_exporter', () => ({
exportDataGrid: jest.fn(
() => new Promise((r) => r({ data: { from: { row: 1, column: 1 }, to: { row: 26, column: 8 } } }))
)
}))
jest.mock('exceljs', () => {
return {
Workbook: jest.fn().mockImplementation(() => {
return {
addWorksheet: () => {},
csv: {
workbook: {},
worksheet: null,
writeBuffer: jest.fn(
() => new Promise((r) => r({ data: { from: { row: 1, column: 1 }, to: { row: 26, column: 8 } } }))
)
}
}
})
}
})
jest.mock('file-saver', () => ({ saveAs: jest.fn() }))
describe('Download grid', () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(downloadComp)
})
it('method handleDownload', () => {
wrapper.vm.downloadCsv()
})
})
I was able to solve by changing the import on my component to
import FileSaver from 'file-saver'
then using it like so,
FileSaver.saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'DataGrid.csv')
Then in the unit test I could just mock the saveAs function like so.
jest.mock('file-saver', () => ({ saveAs: jest.fn() }))