开玩笑嘲笑温斯顿记录仪

时间:2018-12-12 13:07:48

标签: javascript typescript mocking jestjs winston

我正在考虑如何模拟运输方式。文件(来自winston节点模块)。我正在开玩笑,因此__mocks__/winston.ts是自动加载的。我想我不能嘲笑它,因为那里有new

// LoggerFactory.ts
import { transports, TransportInstance } from "winston";

...
    const transportList: TransportInstance[] = [
        new transports.File({
            name: `${tag}-error`,
            filename: `${dirname}${filename}.error.log`,
            json: false,
            level: "error",
            zippedArchive: false,
            maxFiles: 14,
            maxsize: 100000000
        }),
        new transports.File({
            name: `${tag}-info`,
            filename: `${dirname}${filename}.log`,
            json: false,
            level: "info",
            maxFiles: 10,
            zippedArchive: false,
            maxsize: 100000000
        })
    ];
...

// __mocks__/winston.ts
const winston = {
    ????
};
export default winston;

错误:TypeError:无法读取未定义的属性“文件”

1 个答案:

答案 0 :(得分:1)

对于__mocks__/winston.js中的winston测试模拟,我们这样做:

const logger = {
  format: {
    printf: jest.fn(),
    timestamp: jest.fn(),
    simple: jest.fn(),
    colorize: jest.fn(),
    combine: jest.fn()
  },
  transports: {
    Console: jest.fn(),
    File: jest.fn()
  },
  createLogger: jest.fn().mockImplementation(function(creationOpts) {
    return {
      info: jest.fn(),
      warn: jest.fn(),
      error: jest.fn()
    };
  })
};

module.exports = logger;

然后我们可以使用jest.fn()呼叫捕获器来测试记录器。通常,我们不关心日志记录,因此仅用于在测试期间不生成日志文件。