javascript - 开玩笑等待 express 的默认错误处理程序
问题描述
鉴于以下设置:
const express = require("express");
const app = express();
app.get("/", function(req, res, next) {
// explicitly return an error
return next("my error");
});
// made this middleware for the example,
// solution should typically also work for express default error handling
app.use(function(error, req, res, next) {
if (error) {
res.status(500).send({ error });
throw new Error(error); // <- how to test this?
}
next();
});
app.listen(8080, function() {
console.log("server running on 8080");
}); //the server object listens on port 8080
对于测试:
const request = require("supertest");
const app = require("../../app.js");
const spy = jest.spyOn(global.console, "error").mockImplementation();
it("throws an error", async done => {
const res = await request(app).get("/");
expect(res.status).toBe(500);
expect(res.error.text).toContain("my error");
expect(spy).toHaveBeenCalled(); // nothing...
done();
});
使用此示例代码制作了一个 Codesandbox 。不知道如何在其中运行节点测试。
解决方案
async
不应该与 一起使用done
,这会导致测试超时,以防done()
无法达到。
首先,错误处理程序不应该重新抛出错误,除非它是可重用的路由器实例,应该用另一个处理程序来扩充。如果它是连续的最后一个,它应该捕获其中可能发生的同步和异步错误。
问题是默认错误处理程序是异步触发的,因此应该专门等待它:
it("throws an error", async () => {
const spy = jest.spyOn(global.console, "error");
const res = await request(app).get("/");
expect(res.status).toBe(500);
expect(res.error.text).toContain("my error");
await new Promise(resolve = > setTimeout(resolve));
expect(spy).not.toHaveBeenCalled(); // it really shouldn't
});
解决此问题的更正确方法是确保处理错误:
it("throws an error", async () => {
const defaultErrorHandler = jest.fn((err, req, res, next) => {});
app.use(defaultErrorHandler);
const res = await request(app).get("/");
expect(res.status).toBe(500);
expect(res.error.text).toContain("my error");
expect(defaultErrorHandler).not.toHaveBeenCalled();
});
推荐阅读
- java - 是否可以防止 WebView 或任何 View 被破坏?
- sql-server - 替换 CustomerID 字段中的单个数字 SQL Server
- c++ - 找到重叠和下采样散点图
- python - 有没有办法用 PyQt5 捕捉按钮上的悬停事件信号?
- android - 在Android中设置密码时如何在锁定屏幕上显示活动
- python - 处理列表时如何在火花中找到字符串中的索引?
- javascript - useEffect:状态更新后不渲染
- scala - 将使用访问者的 Traversable 迁移到 Scala 2.13 中的 Iterable
- c# - System.Xml.XmlException '根级别的数据无效,第 1 行,位置 1' 当我从 1 xml 文件更改为 5 时出现错误
- docker - Logstash 输出到 ssl elasticsearch