如何在控制台中测试 winston logger 消息的内容

How to test content of winston logger message in console

我正在使用 Winston 作为我的应用程序的记录器,并且正在尝试为记录器消息编写单元测试(使用 Jest)。我特别想确保没有密码传递到我的日志中。

由于记录器输出到 stdout,我无法找到一种方法来访问我的 winston.error 函数输出的内容和 运行 我对日志对象的断言。

我尝试了几种不同的方法来访问记录器的结果,并在谷歌上搜索了解决方案,但没有取得太大成功。这是我的最后一次迭代:

我的logger.js(内容参数在传递给记录器之前已经过清理):

export const error = (content) => {
  return winston.error(content);
};

和我的 logger.spec.js:

const exampleLogs = { "email":"email", "password":"password" };

describe('Passwords are filtered out of Winston logger messages', () => {
  it('Should filter out password data from "error" level errors', () => {
    logger.error(exampleLogs);
    const result = jest.fn();
    expect(result).not.toHaveProperty('password');
  });
});

即使密码密钥就在那里,测试也通过了。当我 console.log(result) 我得到一个模拟构造函数对象时:

{ [Function: mockConstructor]
      _isMockFunction: true,
      getMockImplementation: [Function],
      mock: [Getter/Setter],
      mockClear: [Function],
      mockReset: [Function],
      mockRestore: [Function],
      mockReturnValueOnce: [Function],
      mockResolvedValueOnce: [Function],
      mockRejectedValueOnce: [Function],
      mockReturnValue: [Function],
      mockResolvedValue: [Function],
      mockRejectedValue: [Function],
      mockImplementationOnce: [Function],
      mockImplementation: [Function],
      mockReturnThis: [Function],
      mockName: [Function],
      getMockName: [Function] }

但我希望看到我的 exampleLogs 对象...如何访问记录器发送到 stdout 的对象?任何帮助将不胜感激!

要模拟您的 logger.error 函数,您必须在使用对象调用它之前将 jest.fn() 属性赋予它。但我想这不是你想要的,对吧?你不想改变记录器的行为,你只想检查它的调用。如果是这样的话,你想要一个间谍而不是一个模拟。

但是还有另一种检查记录器输出的方法。考虑将文件传输添加到您的 winston 配置 (https://github.com/winstonjs/winston/blob/master/docs/transports.md)。然后读取文件并检查是否有预期的输出,然后删除文件。

Pedro 的解决方案很棒。但是,我使用 stream 作为传输以将输出保存在内存中。然后,阅读起来更容易,我不需要删除任何文件。

你可以在这里找到一个例子:https://github.com/winstonjs/winston/issues/809#issuecomment-598966499