Jest - getting error when mocking FS modules and calling config module - jestjs

I'm writing unit tests with Jest trying to test a module which uses FS.
The module file:
import fs from 'fs';
import logger from './logger.utils';
export const getNumberOfFiles = async (targetDir: string): Promise<number> => {
// get number of folders
logger.info(`getNumberOfFiles from ${targetDir}/${fileName}`);
const numberOfFiles = await fs.readdirSync(targetDir);
return numberOfFiles.length;
};
Test file
import fs from 'fs';
import { getNumberOfFiles } from '../../src/utils/fs.utils';
jest.mock('fs');
describe('fs.utils', () => {
describe('getNumberOfFiles', () => {
it('Should return number', async () => {
fs.readdirSync = jest.fn();
const readdirSyncMock = fs.readdirSync = jest.fn();
readdirSyncMock.mockResolvedValue([1, 2, 3]);
const result = await getNumberOfFiles('targetDir');
expect(result).toEqual(3);
expect(readdirSyncMock.mock.calls.length).toEqual(1);
});
});
});
When I run the test file, I get the following error:
Config file ..../config/runtime.json cannot be read. Error code is: undefined. Error message is: Cannot read property 'replace' of undefined
1 | const cheggLogger = require('#chegg/logger');
2 | import loggingContext from './loggingContext';
> 3 | import config from 'config';
| ^
4 | import os from 'os';
5 | import constants from '../../config/constants';
6 |
at Config.Object.<anonymous>.util.parseFile (node_modules/config/lib/config.js:789:13)
at Config.Object.<anonymous>.util.loadFileConfigs (node_modules/config/lib/config.js:666:26)
at new Config (node_modules/config/lib/config.js:116:27)
at Object.<anonymous> (node_modules/config/lib/config.js:1459:31)
at Object.<anonymous> (src/utils/logger.utils.ts:3:1)
Content of logger.utils.ts
const internalLogger = require('internalLogger');
import loggingContext from './loggingContext';
import config from 'config';
import os from 'os';
import constants from '../../config/constants';
const logger = internalLogger.createLogger({
level: config.get(constants.LOG_LEVEL)
});
export default logger;
I assume that config is using FS, and once I mock the module, it fails.
How can I resolve this? Please advise

I'm guessing the problem comes from config also using the fs api but you are now mock entire module fs which makes all methods should be mocked before using.
But I have an idea for you by using jest.doMock which you can provide a factory for each test and just mock only method we need. Here is a draft idea:
describe('fs.utils', () => {
describe('getNumberOfFiles', () => {
it('Should return number', async () => {
jest.doMock('fs', () => ({
// Keep other methods still working so `config` or others can use
// so make sure we don't break anything
...jest.requireActual('fs'),
readdirSync: jest.fn(pathUrl => {
// Mock for our test path since `config` also uses this method :(
return pathUrl === 'targetDir' ? Promise.resolve([1, 2, 3]) : jest.requireActual('fs').readdirSync(pathUrl)
})
}));
// One of the thing we should change is to switch `require` here
// to make sure the mock is happened before we actually require the code
// we can also use `import` here but requires us do a bit more thing
// so I keep thing simple by using `require`
const {getNumberOfFiles} = require('../../src/utils/fs.utils');
const result = await getNumberOfFiles('targetDir');
expect(result).toEqual(3);
// you might stop assert this as well
// expect(readdirSyncMock.mock.calls.length).toEqual(1);
});
});
});
Just also want to check, if you created a config file as described here: https://www.npmjs.com/package/config#quick-start

Related

How to spyOn an internal static function call?

I have the following event handler and I want to test that updateOrAddNew is being called.
const { Events } = require('client');
const User = require('../models/User');
module.exports = {
name: Events.MemberAdd,
async execute(member) {
User.updateOrAddNew(member);
}
}
I've written the following test:
import {it, expect, vi } from 'vitest';
import User from '../models/User';
import memberAdd from './memberAdd';
it('calls updateOrAddNew on memberAdd', async () => {
const spy = vi.spyOn(User, 'updateOrAddNew').mockReturnValue(true);
User.updateOrAddNew = spy;
const member = {...};
await memberAdd.execute(member);
expect(spy).toBeCalled();
});
I've tried numerous different syntax but the spy is never called. updateOrAddNew is a static method. How can I test whether it's being called when memberAdd.execute is run?
I'm pretty new to testing so any help would be appreciated.
What if you declare in that file globally like this:
jest.spyOn(User, 'updateOrAddNew').mockReturnValue(true);
This should update any usage of this method with mock

Mocking of a function within a function not working in jest with jest.spyOn

I'm trying to write a test for a function that downloads an Excel file within my React app.
I understand that I need to mock certain functionality, but it doesn't seem to be working according to everything that I have read online.
A basic mock that works is this:
import FileSaver from 'file-saver'
import { xlsxExport } from './functions'
// other code...
test('saveAs', async () => {
const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
FileSaver.saveAs('test')
expect(saveAsSpy).toHaveBeenCalledWith('test')
})
The above works: FileSaver.saveAs was successfully mocked. However, I am utilising FileSaver.saveAs within another function that I wish to test and the mocking does not seem to transfer into that. functions.ts and functions.tests.ts below.
functions.ts:
import { Dictionary } from './interfaces'
import * as ExcelJS from 'exceljs'
import FileSaver from 'file-saver'
export function xlsxExport(data: Dictionary<any>[], fileName?: string, tabName?: string) {
const workbook = new ExcelJS.Workbook()
const worksheet = workbook.addWorksheet(tabName || 'export')
// Get columns from first item in data
worksheet.columns = Object.keys(data[0]).map((key: string) => ({ header: key, key: key }))
// Write each item as a row
for (const row of data) {
worksheet.addRow(row)
}
// Download the file
workbook.xlsx.writeBuffer().then(function (buffer) {
const blob = new Blob([buffer], { type: 'applicationi/xlsx' })
FileSaver.saveAs(blob, (fileName || 'excel_export') + '.xlsx')
})
}
functions.tests.ts
import FileSaver from 'file-saver'
import { xlsxExport } from './functions'
// ...other code
test('xlsxExport', async () => {
const saveAsSpy = jest.spyOn(FileSaver, 'saveAs')
xlsxExport(myArrayOfDicts, 'test_download')
expect(saveAsSpy).toHaveBeenCalledWith('something, anything')
})
Error:
TypeError: Cannot read properties of null (reading 'createElement')
at Function.saveAs (C:\dev\pcig-react\node_modules\file-saver\src\FileSaver.js:92:9)
at C:\dev\pcig-react\src\common\functions.ts:221:19
at processTicksAndRejections (node:internal/process/task_queues:95:5)
Node.js v19.3.0
FAIL src/common/functions.test.ts
● Test suite failed to run
Jest worker encountered 4 child process exceptions, exceeding retry limit
at ChildProcessWorker.initialize (node_modules/jest-runner/node_modules/jest-worker/build/workers/ChildProcessWorker.js:185:21)
It is trying to call the non-mocked FileSaver.saveAs (line 221 of my file) within xlsxExport.
How can I get it to call the mocked version?

why can't you mock a re-exported primitive value?

I'm trying to change the value of a primitive config object during tests. One of my files under test re-exports a primitive that is conditional on the config values.
I'm finding that when the value is wrapped in a function, then mocking it and asserting on it works perfectly.
However when the value is re-exported as a primitive, the value is not mocked, and is undefined.
Simplified example:
config.ts
export const config = {
environment: 'test'
};
app.ts
import { config } from './config';
export const app = () => config.environment;
export const environment = config.environment;
app.spec.ts
import { app, environment } from './app';
import * as config from './config';
jest.mock('./config', () => ({
config: {},
}));
beforeEach(() => {
jest.resetAllMocks();
});
const mockConfig = config.config as jest.Mocked<typeof config.config>;
test('app', () => {
mockConfig.environment = 'prod';
expect(app()).toEqual('prod');
});
test('environment', () => {
mockConfig.environment = 'nonprod';
expect(environment).toEqual('nonprod');
});
The first test passes, but the second test "environment" fails. Why?
✕ environment (3 ms)
● environment
expect(received).toEqual(expected) // deep equality
Expected: "nonprod"
Received: undefined
19 | test('environment', () => {
20 | mockConfig.environment = 'nonprod';
> 21 | expect(environment).toEqual('nonprod');
| ^
22 | });
23 |
at Object.<anonymous> (config/app.spec.ts:21:29)
The problem could be related with the order files are read. The app file is the first one to be read, and then the config file is read because its imported on the app one. But, probably the app code run first, so the variable was set as undefined (because the config one had not a value at the time).
The same does not happen with the app function, because it reads the config variable only after the function is called. And at that time, the variable already was set.

jest mock requires requireActual

Its unclear for me why requireActual (3) is required to use the mock in __mocks__/global.ts (2) instead of global.ts (1) inside app.ts
According to the docs https://jestjs.io/docs/jest-object#jestrequireactualmodulename it says
Returns the actual module instead of a mock, bypassing all checks on
whether the module should receive a mock implementation or not.
What are the mentioned checks?
// __mocks__/global.ts
export const globalConfig = {
configA: "mockedConfigA"
};
export const globalLibA = jest.fn((msg) => {
return msg + "+mockedLibA"
});
// app.ts
import { globalConfig, globalLibA } from "./global"
export const app = function (msg) {
console.log("Called app")
return globalLibA(msg);
}
export const globalConfigConfigA = globalConfig.configA;
Full source: https://github.com/Trenrod/testjest/tree/master/src

Testing async methods using Mocha, Chai, node.js

I have a very simple code structure like this
TestWorks.ts
const axios = require('axios');
export class TestWorks{
async getUsersList(param1:TestModel, userDetail:any){
console.log("BEGIN -- ... ");
And then this is my test class
MyTest.ts
const testworks = require("../src/interfaces/TestService/TestWorks");
it('Get Users', async () => {
var x = await testworks.getUsersList({}, {});
expect(x).to.be.an("object");
});
but I am seeing the following error, unable to figure out what the issue could be. The paths are definitely right, not an issue with the file paths of where the files are
Get Users:
TypeError: testworks.getUsersList is not a function
at C:\Users\xxxxxx\Documents\xxxxx\test\test-server.test.ts:53:28
testworks refers to the module (or whatever TypeScript exports) because you use require(). You should use import for TypeScript modules.
import { TestWorks } from '../src/interfaces/TestService/TestWorks';

Resources