【发布时间】:2020-03-18 15:15:41
【问题描述】:
我正在做一个 POST 来创建一个项目并将新创建的项目作为响应发送回客户端。
async (req, res, next) => {
const item = await createItem(xx, yy, zz);
res.send(201, item);
}
现在我还想在创建项目后发送通知但也要在响应客户端后发送通知 - 以尽可能快地发出请求。
async (req, res, next) => {
const item = await createItem(xx, yy, zz);
res.send(201, item);
sendNotification(item);
}
如果我想使用 jest + supertest 进行测试,它会是这样的:
test('return 201', () => {
const app = require('./');
return request(app)
.post('/api/items')
.send({})
.expect(201)
.then(response => {
// test something more
});
}
但是我如何测试sendNotification() 是否被调用?
【问题讨论】:
-
sendNotification()使用res吗?那是行不通的。基本上,send结束 HTTP 响应。尽管您可以在res.send之后访问代码,但对res的任何引用都将失败。sendNotification是做什么的? -
@PruthviKumar 它发送推送通知并且没有使用
res。 -
好吧,在这种情况下,您可以使用
.done(() => {//test something set/used by sendnotification})来验证是否调用了sendNotification。 -
@PruthviKumar 不起作用,因为那时还没有调用它
标签: node.js express jestjs restify supertest