模拟fs功能与开玩笑

Oya*_*abi 7 unit-testing fs node.js winston jestjs

首先,我是新手es6jest.

我有一个Logger实例化的类winston,我想测试它.

这是我的代码:

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();
Run Code Online (Sandbox Code Playgroud)

我想测试我的功能createLogDir().我的头脑,我认为测试fs.existsSync的状态是个好主意.如果fs.existsSync返回false,fs.mkdirSync必须调用.所以我尝试写一些jest测试:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

但是,我有一个错误:

  ? 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)
Run Code Online (Sandbox Code Playgroud)

你能帮我调试和测试我的功能吗?

问候.

Bil*_*lly 14

这里的错误是因为它正在寻找一个fs.mkdirSync在你的logger对象上调用的方法,它不存在.如果你有权访问fs测试中的模块,那么你会窥探这样的mkdirSync方法:

jest.spyOn(fs, 'mkdirSync');
Run Code Online (Sandbox Code Playgroud)

但是,我认为你需要采取不同的方法.

您的createLogDir函数是一个静态方法 - 意味着它只能在类上调用,而不能在该类的实例上调用(new Logger()是该类的实例Logger).因此,为了测试该函数,您需要导出类而不是它的实例,即:

module.exports = Logger;
Run Code Online (Sandbox Code Playgroud)

然后你可以进行以下测试:

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();
});
Run Code Online (Sandbox Code Playgroud)

注意:看起来你正在混合CommonJS和es6模块语法(export default是es6) - 我会试着坚持一个或另一个

  • 我认为这种模式不允许恢复真正的 FS 方法。这会以可能影响其他测试的方式永久性地改变测试环境。你需要使用 `jest.spyOn(fs, 'mkdirSync')` 以便你以后可以使用 `fs.mkdirSync.mockRestore()`。 (3认同)