【问题标题】:Mocking winston logger in jest开玩笑地嘲笑温斯顿记录器
【发布时间】:2019-05-13 14:24:32
【问题描述】:

我正在考虑如何模拟传输。文件(来自 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:无法读取未定义的属性“文件”

【问题讨论】:

  • 我还想为使用 Winston 的记录器实现编写测试。你找到解决办法了吗?

标签: javascript typescript mocking jestjs winston


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多