node version: 14.20.0
jest version: 28.1.1
ts-jest version: 28.0.5
I have following function which is to be tested
uploadFile.ts
import * as fs from 'fs';
export async function uploadFile(containerName, customerId, fileName, filePath, logCtx){
fs.stat(filePath, (err, stats) => {
if (err) {
logger.error({err, ...logCtx}, `File doesn't exist. File path: ${filePath}`);
} else {
logger.info(logCtx, `File size: ${stats.size}`);
if(stats.size < 1){
logger.error({err, ...logCtx}, `Byte size is ${stats.size} - File is empty. File path: ${filePath}`);
throw new Error("File is empty.")
}
}
});
// do some other things
}
The uploadFile function uses fs module and I decided to mock it since we don't need to do anything with files for testing
uploadFile.test.js
// mock fs package
const fs = { stat: jest.fn(), createReadStream: jest.fn() };
jest.mock("fs", () => {
return fs;
});
it("should call fs.stat once", async () => {
// Arrange
const { uploadFile } = require("../../../lib/global/uploadFile");
const containerName = "qz";
const customerId = "w3";
const fileName = "none.pdf";
const filePath = "src/services/none.pdf";
const logCtx = {};
// Act
await uploadFile(containerName, customerId, fileName, filePath, logCtx);
// Assert
expect(fs.stat).toBeCalledWith(filePath, expect.any(Function));
expect(fs.stat).toBeCalledTimes(1);
});
when running the above test file, test case fails and shows the following error
● should call fs.stat once
require-at: stat 'C:\guardian group\c360-accounts' failed: Fs.statSync is not a function
at makeIt (node_modules/require-at/require-at.js:19:15)
at requireAt (node_modules/require-at/require-at.js:35:10)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/src/index.ts:318:64)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/index.js:8:13)
I have changed the mock of "fs" to the following hopeing it would resolve the error, and it is showing a different error instead.
const fs = { stat: jest.fn(), createReadStream: jest.fn(), statSync: jest.fn() };
The error
● should call fs.stat once
require-at: not a directory: 'C:\guardian group\c360-accounts'
at makeIt (node_modules/require-at/require-at.js:23:28)
at makeIt (node_modules/require-at/require-at.js:24:16)
at requireAt (node_modules/require-at/require-at.js:35:10)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/src/index.ts:318:64)
at Object.<anonymous> (node_modules/mongoose/node_modules/mongodb/node_modules/optional-require/index.js:8:13)
What's happening here, am I missing something?
Thanks in advance