Here is some code using xlsx library (=sheetjs):
import { read } from 'xlsx';
export default function foo(file){
return read(file);
};
and here is a unit test for it:
import foo from '../../../src/components/upload/demo';
it('foo', () => {
const mockedXlsx = {
read: () => 'mocked_result'
};
jest.mock('xlsx', () => mockedXlsx);
const mockedFile = {
arrayBuffer: () => {}
};
spyOn(mockedFile, 'arrayBuffer');
const result = foo(mockedFile);
expect(result).toBe('mocked_result');
expect(mockedFile.arrayBuffer).toHaveBeenCalled();
});
My package.json includes following dependency:
"xlsx": "https://cdn.sheetjs.com/xlsx-0.19.0/xlsx-0.19.0.tgz"
Instead of calling my mocked read
function, the original function is called and I get the error
TypeError: e.slice is not a function
=> How should I adapt my code, so that jest.mock
replaces the original read function?
I already tried to
a) Include __esModule: true
in mockedXlsx
b) Include an entry for xlsx in jest.config moduleNameMapper:
'^xlsx$': '<rootDir>/node_modules/xlsx/dist/xlsx.full.min.js'
As a workaround, I changed the import to
import xlsx from 'xlsx';
I use the same import in the test and then, instead of jest.mock('xlsx',...)
I can use
spyOn(xlsx,'read')