首页 > 解决方案 > 开玩笑地嘲笑温斯顿记录器

问题描述

我正在考虑如何模拟运输。文件(来自 winston 节点模块)。我正在使用 jest,所以__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:无法读取未定义的属性“文件”

标签: javascripttypescriptmockingjestjswinston

解决方案


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

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()调用捕获器来测试记录器。通常我们不关心日志,所以这只是用来在测试期间不生成日志文件。


推荐阅读