Javascript 如何在控制台中测试winston logger消息的内容
我正在使用Winston作为我应用程序的记录器,我正在尝试为记录器消息编写单元测试(使用Jest)。我特别想确保没有密码被传递到我的日志中 由于记录器输出到Javascript 如何在控制台中测试winston logger消息的内容,javascript,jestjs,winston,Javascript,Jestjs,Winston,我正在使用Winston作为我应用程序的记录器,我正在尝试为记录器消息编写单元测试(使用Jest)。我特别想确保没有密码被传递到我的日志中 由于记录器输出到stdout,因此我无法找到访问我的winston.error函数输出的内容并在日志对象上运行我的断言的方法 我尝试了几种不同的方法来访问记录器的结果,并在谷歌上搜索解决方案,但没有取得多大成功。这是我的最后一次迭代: My logger.js(在将内容参数传递给记录器之前对其进行清理): 还有我的logger.spec.js: const
stdout
,因此我无法找到访问我的winston.error
函数输出的内容并在日志对象上运行我的断言的方法
我尝试了几种不同的方法来访问记录器的结果,并在谷歌上搜索解决方案,但没有取得多大成功。这是我的最后一次迭代:
My logger.js(在将内容参数传递给记录器之前对其进行清理):
还有我的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] }
但我希望看到我的
示例日志
对象。。。如何访问记录器发送到标准输出的对象?任何帮助都将不胜感激 要模拟logger.error函数,必须在使用对象调用它之前将jest.fn()属性赋予它。但我想那不是你想要的,对吧?您不想更改记录器行为,只想检查其调用。如果是这样的话,你想要一个间谍而不是一个骗子
但是还有另一种方法可以检查记录器输出。考虑将文件传输添加到温斯顿配置()中。然后读取文件并检查是否有预期的输出,然后删除该文件。Pedro的解决方案非常好。但是,我使用
stream
作为传输,将输出保存在内存中。然后,它更容易阅读,我不需要删除任何文件
你可以在这里找到一个例子:谢谢佩德罗!没错-我正在尝试获取记录器发出的实际结果。通常情况下,我的记录器会推送到splunk类型的服务,但在本地,它只会发送到stdout。我想你的运输计划行得通,我现在读一下,让你知道。谢谢
{ [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] }