简体   繁体   English

jest winston format.errors 不是 function

[英]jest winston format.errors is not a function

I have an app that uses winston for logging.我有一个使用 winston 进行日志记录的应用程序。 I am trying to setup a jest test for a function, that calls another function, etc., and the test for the function eventually fails at an attempt to use winston exported functions:我正在尝试为 function 设置一个玩笑测试,调用另一个 function 等,而 function 的测试最终在尝试使用 winston 导出函数时失败:

services\__tests__>jest search.test.js
 FAIL  ./search.test.js
  ● Test suite failed to run

    TypeError: format.errors is not a function

      26 | const logger = createLogger({
      27 |   level: config.logging.level,
    > 28 |   format: format.combine(format.errors({ stack: true }), errorStackFormat(), config.logging.logFormat()),
         |                                 ^
      29 |   transports: [
      30 |     new transports.Console({
      31 |       stderrLevels: ['error', 'critical'],

      at Object.<anonymous> (helpers/logger.js:28:33)
      at Object.<anonymous> (db/connection/connection.js:2:16)

/search.test.js /search.test.js

jest.mock('winston', () => ({
  format: jest.fn(() => ({
    errors: jest.fn(),
    combine: jest.fn(),
    apply: jest.fn(),
  })),
  createLogger: jest.fn().mockImplementation(() => ({
    info: jest.fn(),
    warn: jest.fn(),
    error: jest.fn(),
  })),
  transports: {
    Console: jest.fn(),
  },
}));

const search = require('../search');
process.env.NODE_ENV = 'development';

describe('services/search.js', () => {
  it('searches ', async () => {
    const query = {
      mpn: '5555555555',
    };

    expect(
      await search(query).then((result) => {
        console.log('result', result);
        return result;
      })
    ).toEqual(['000']);
  });
});

helpers/logger.js助手/logger.js

const { createLogger, format, transports } = require('winston');
const config = require('../config');
require('express-async-errors');

const errorStackFormat = format((info) => {
  if (info.level === 'error') {
    if (!/^{.*?}$/.test(info.message)) return info;

    const { code, reason, status, message } = JSON.parse(info.message);
    return {
      ...info,
      code,
      reason,
      status,
      message,
    };
  }

  return info;
});

const logger = createLogger({
  level: config.logging.level,
  format: format.combine(format.errors({ stack: true }), errorStackFormat(), config.logging.logFormat()),
  transports: [
    new transports.Console({
      stderrLevels: ['error', 'critical'],
    }),
  ],
  exceptionHandlers: [new transports.Console(config.logging.format)],
  exitOnError: true,
});

module.exports = logger;

If I try to only have format as an object, it fails the test on const errorStackFormat = format((info) because it's looking for format to be a function, so the mock needs to have format as a function, and also have properties (like errors ) that are functions as well.如果我尝试仅将format设置为 object,则它无法通过const errorStackFormat = format((info)的测试,因为它正在寻找format为 function,因此模拟需要将format设置为 function,并且还具有属性(像errors )也是功能。

How can I get format.errors to work in the mock?我怎样才能让format.errors在模拟中工作? I'm not doing something right, please help me figure out what I am doing wrong:) Thanks!我做错了什么,请帮我弄清楚我做错了什么:)谢谢!

Well I figured it out, at least it's not complaining anymore about the original error.好吧,我想通了,至少它不再抱怨原来的错误了。 I needed to use my logger function that uses winston, like so:我需要使用使用 winston 的记录器 function,如下所示:

jest.mock('../../helpers/logger', () => jest.fn());
const logger = require('../../helpers/logger');

logger.mockImplementation(() => () => ({
  format: jest.fn(() => ({
    errors: jest.fn(),
    combine: jest.fn(),
    apply: jest.fn(),
  })),
  createLogger: jest.fn().mockImplementation(() => ({
    info: jest.fn(),
    warn: jest.fn(),
    error: jest.fn(),
  })),
  transports: {
    Console: jest.fn(),
  },
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM