Skip to content

react vitest with local file

i try to write a end-to-end vitest for my react component that is using read-excel-file. my goal is to test for

  • select known file from disc
  • check if rows contain known data

for this i tried various ways of loading the file into my vitest... with this i cam near working:

import path from "node:path";
import { openAsBlob } from "node:fs";

        console.log("__dirname", __dirname);
        const xlsx_file_path = path.join(__dirname, "people_10.xlsx");
        // const xlsx_file_path_abs = path.resolve(xlsx_file_path);
        let blob = undefined;
        try {
            blob = await openAsBlob(xlsx_file_path, {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
        } catch (error) {
            console.log(error);
        }

        console.log("blob", blob);
        // https://reactjs.org/link/wrap-tests-with-act
        await act(async () => {
            /* fire events that update state */
            await user.upload(input, blob.);
        });

the onChange handler of the input triggers the loading.

my react component is working fine in the browser - but with the code above i get a

importFileXLSX Blob {
  size: 8190,
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
Error: invalid zip data
    at unzipSync (file:///home/stefan/myproject/node_modules/fflate/esm/index.mjs:2526:13)
    at unpackXlsxArrayBuffer (file:///home/stefan/myproject/node_modules/read-excel-file/source/read/unpackXlsxFileBrowser.js:25:19)
    at unpackXlsxFile (file:///home/stefan/myproject/node_modules/read-excel-file/source/read/unpackXlsxFileBrowser.js:15:9)
    at Proxy.readXlsxFile (file:///home/stefan/myproject/node_modules/read-excel-file/source/read/readXlsxFileBrowser.js:14:9)
    at Module.importFileXLSX (/home/stefan/myproject/src/components/MyImportFile/dataImportExport.js:73:24)
    at handleImportFileXLSX (/home/stefan/myproject/src/components/MyImportFile/index.jsx:66:13)
    at HTMLUnknownElement.callCallback (/home/stefan/myproject/node_modules/react-dom/cjs/react-dom.development.js:4164:14)
    at HTMLUnknownElement.callTheUserObjectsOperation (/home/stefan/myproject/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
    at innerInvokeEventListeners (/home/stefan/myproject/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:350:25)
    at invokeEventListeners (/home/stefan/myproject/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:286:3) {
  code: 13
}

all other methods of file loading i tried did result in

importFileXLSX Blob {}
TypeError: input.arrayBuffer is not a function

seems with the later i did not get any content in the blob...

do you have any idea what is going on with the Error: invalid zip data thing? maybe related to that it is not really running in a browser?

any help and tips are welcome.

i also posted a detailed question at stackoverflow