Jest / NodeJS, как построить тест для "unhandledRejection" - PullRequest
1 голос
/ 02 марта 2020

Я пытаюсь получить 100% покрытие.

Я застрял при создании теста для этой части моего кода:

// Manually throwing the exception will let winston handle the logging
process.on("unhandledRejection", (ex) => {
  throw ex;
});

Я пытался использовать следующее:

const logger = require("../../../startup/logging");

describe("startup / logging", () => {
  it("should log the error in case of unhandledRejection", () => {
    process.emit("unhandledRejection");
    const loggerError = jest.spyOn(logger, "error");
    expect(loggerError).toHaveBeenCalled();
  });
});

Но тест завершается неудачно с: thrown: undefined

Это полный код ведения журнала. js:

const { createLogger, format, transports } = require("winston");
require("winston-mongodb");
// This will forward the error in the pipeline to our error handler
require("express-async-errors");

// Manually throwing the exception will let winston handle the logging
process.on("unhandledRejection", (ex) => {
  throw ex;
});

// Log to files
const logger = createLogger({
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    format.errors({ stack: true }),
    format.splat(),
    format.json()
  ),
  transports: [
    new transports.File({filename: "./logs/combined.log", level: "verbose"}),
  ],
  transports: [
    new transports.File({filename: "./logs/error.log", level: "error"}),
    new transports.File({filename: "./logs/combined.log"}),
  ],
  exceptionHandlers: [
    new transports.File({ filename: "./logs/exceptions.log" }),
    new transports.File({ filename: "./logs/combined.log" }),
  ],
  handleExceptions: true,
});

// Log to database
logger.add(new transports.MongoDB({
  level: "error",
  db: "mongodb://localhost:27017/rest-api-mongodb",
  options: {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  },
  metaKey: "stack",
  handleExceptions: true,
}));

module.exports = logger;

Это промежуточное ПО ошибки это срабатывает в случае unhandledRejection:

// Winston is a logger, it allows to store errors in a log and mongoDB
const logger = require("../startup/logging");

// This function will handle all errors in the router
// It works thanks to require("express-async-errors"); that forwards the error in the pipeline

// It does not work outside of the context of express
module.exports = function (err, req, res, next) {
  logger.error(err.message, err);
  // error, warn, info, berbose, debug, silly
  res.status(500).send("Something on the server failed.");
}

Любая помощь приветствуется!

Ответы [ 2 ]

2 голосов
/ 02 марта 2020

Попробуйте вызвать unhandledRejection, используя реальный необработанный отказ. Например, вызовите Promise.reject(), не подключая обработчик.

0 голосов
/ 02 марта 2020

Поиграв с кодом, я заставил его работать следующим образом:

require("../../../startup/logging");

describe("startup / logging", () => {
  it("should throw an error if there is an unhandledRejection", () => {
    const emitUnhandledRejection = () => process.emit("unhandledRejection");
    expect(emitUnhandledRejection).toThrow();
  });
});
...