26

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.

Here my code :

const winston = require('winston');
const fs = require('fs');
const path = require('path');
const config = require('../config.json');

class Logger {
  constructor() {
    Logger.createLogDir(Logger.logDir);
    this.logger = winston.createLogger({
      level: 'info',
      format: winston.format.json(),
      transports: [
        new (winston.transports.Console)({
          format: winston.format.combine(
            winston.format.colorize({ all: true }),
            winston.format.simple(),
          ),
        }),
        new (winston.transports.File)({
          filename: path.join(Logger.logDir, '/error.log'),
          level: 'error',
        }),
        new (winston.transports.File)({
          filename: path.join(Logger.logDir, '/info.log'),
          level: 'info',
        }),
        new (winston.transports.File)({
          filename: path.join(Logger.logDir, '/combined.log'),
        }),
      ],
    });
  }

  static get logDir() {
    return (config.logDir == null) ? 'log' : config.logDir;
  }

  static createLogDir(logDir) {
    if (!fs.existsSync(logDir)) {
      // Create the directory if it does not exist
      fs.mkdirSync(logDir);
    }
  }
}

exports.logger = new Logger().logger;
export default new Logger();

I would like to test my function createLogDir(). I my head, I think it's a good idea to test the state of fs.existsSync. If fs.existsSync return false, fs.mkdirSync must be called. So I try to write some jest test :

describe('logDir configuration', () => {
  test('default path must be used', () => {
    const logger = require('./logger');
    jest.mock('fs');
    fs.existsSync = jest.fn();
    fs.existsSync.mockReturnValue(false);
    const mkdirSync = jest.spyOn(logger, 'fs.mkdirSync');
    expect(mkdirSync).toHaveBeenCalled();
  });
});

However, I've got an error :

  ● logDir configuration › default path must be used

    Cannot spy the fs.mkdirSync property because it is not a function; undefined given instead

      18 |     fs.existsSync = jest.fn();
      19 |     fs.existsSync.mockReturnValue(true);
    > 20 |     const mkdirSync = jest.spyOn(logger, 'fs.mkdirSync');
      21 |     expect(mkdirSync).toHaveBeenCalled();
      22 |   });
      23 | });

      at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:590:15)
      at Object.test (src/logger.test.js:20:28)

Can you help me to debug and test my function please ?

Regards.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Oyabi
  • 824
  • 3
  • 10
  • 27

2 Answers2

42

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

Billy Reilly
  • 1,422
  • 11
  • 11
  • 5
    I think this pattern doesn't allow for the real FS methods to be restored. This permanently alters the test environment in ways that could affect other tests. You'll need to use `jest.spyOn(fs, 'mkdirSync')` so you can later do `fs.mkdirSync.mockRestore()`. – Tom Dec 01 '18 at 21:41
  • @Billy winston will automatically create new folder do we need to write extra code for that one – Learner Jan 19 '19 at 15:00
  • @Billy i was also implementing the above one can you check this one https://stackoverflow.com/questions/54250372/logger-implementation-using-winston-morgan-and-winston-daily-rotate-file , will be a help for me – Learner Jan 19 '19 at 15:01
  • @Tom you're right, have changed to auto mocking so it wouldn't affect other tests – Billy Reilly Feb 16 '19 at 12:24
0

I think you can fix this with

import * as fs from 'fs'

then

jest.doMock('fs', () => fs) 

this should fix your problem.

Sam
  • 11
  • 3