First of all, I\'m new to es6
and jest
.
I have a Logger
class for instantiate winston
and I would like to test it
The error there is because it is looking for a method called fs.mkdirSync
on your logger
object, which doesn't exist. If you had access to the fs
module in your test then you would spy on the mkdirSync
method like this:
jest.spyOn(fs, 'mkdirSync');
However, I think you need to take a different approach.
Your createLogDir
function is a static method - meaning that it can only be called on the class, and not on an instance of that class (new Logger()
is an instance of the class Logger
). Therefore, in order to test that function you need to export the class and not an instance of it, i.e.:
module.exports = Logger;
Then you could have the following tests:
const Logger = require('./logger');
const fs = require('fs');
jest.mock('fs') // this auto mocks all methods on fs - so you can treat fs.existsSync and fs.mkdirSync like you would jest.fn()
it('should create a new log directory if one doesn\'t already exist', () => {
// set up existsSync to meet the `if` condition
fs.existsSync.mockReturnValue(false);
// call the function that you want to test
Logger.createLogDir('test-path');
// make your assertion
expect(fs.mkdirSync).toHaveBeenCalled();
});
it('should NOT create a new log directory if one already exists', () => {
// set up existsSync to FAIL the `if` condition
fs.existsSync.mockReturnValue(true);
Logger.createLogDir('test-path');
expect(fs.mkdirSync).not.toHaveBeenCalled();
});
Note: it looks like you're mixing CommonJS and es6 module syntax (export default
is es6) - I would try to stick to one or the other