I am currently attempting to write unit tests for the following file:
import { readFileSync } from 'fs';
import logger from './logger.utils';
export const readFile = async (targetDir: string, fileName: string): Promise<string> => {
logger.info(`start reading from ${targetDir}/${fileName}`);
const data = readFileSync(`${targetDir}/${fileName}`, {encoding: 'utf8', flag: 'r'});
return data;
};
jest test file
import { mocked } from 'ts-jest/utils';
import fs from 'fs';
jest.mock('fs');
import * as fsUtils from '../../src/utils/fs.utils';
let readFileSyncMock: jest.SpyInstance;
describe('fs.utils', () => {
describe('readFile', () => {
afterEach(() => {
readFileSyncMock.mockReset();
});
afterAll(() => {
readFileSyncMock.mockRestore();
});
it('should create a new log directory if one doesn\'t already exist', async () => {
mocked(fs.readFileSync as jest.Mock).mockImplementation(() => { ('some string') });
const fileData = await fsUtils.readFile('target_directory', 'file_name');
expect(fileData).toEqual('some string');
});
});
});
Upon running the test, I encounter the following error:
Config file /Users/dfaizulaev/Documents/projectname/config/runtime.json cannot be read. Error code is: undefined. Error message is: Cannot read property 'replace' of undefined
1 | import loggingContext from './loggingContext';
> 2 | import config from 'config';
| ^
3 | import os from 'os';
4 | import constants from '../../config/constants';
5 |
at Config.Object.<anonymous>.util.parseFile (node_modules/config/lib/config.js:821:13)
at Config.Object.<anonymous>.util.loadFileConfigs (node_modules/config/lib/config.js:697:26)
at new Config (node_modules/config/lib/config.js:116:27)
at Object.<anonymous> (node_modules/config/lib/config.js:1492:31)
at Object.<anonymous> (src/utils/logger.utils.ts:3:1)
The error is originating from the logger file that is being imported by the fs module file mentioned above.
logger.utils
file
import loggingContext from './loggingContext';
import config from 'config';
import os from 'os';
import constants from '../../config/constants';
const LOG_LEVEL: string = config.get(constants.LOG_LEVEL);
....additional logic....
I suspect that the error is due to my incorrect mocking of the fs
module, despite trying multiple approaches, I continue to receive this error.
Please share your guidance and insight.