【发布时间】:2022-01-22 22:52:45
【问题描述】:
我目前正在尝试对我的 HTTPS 功能进行单元测试。我想测试我的错误响应,所以我自愿在我的 https 函数中引发异常。我发现console.debug(e) 中显示的错误,但我在单元测试中提供的res.status().json() 从未被调用,因此done() 函数也从未被调用。
但是,好像onCreateUserAndAgency()成功的时候,我提供的res.json()被调用了,测试成功了。
如果发生异常,是否有替换 Response 对象的步骤?我是不是做错了什么?
我使用的堆栈是Firebase Functions,其中Typescript 和Mocha 用于单元测试。
export default functions.https.onRequest((req, res) => {
/* here, when I put res.status(200).json({}), the test's successful so it means done() is called */
onCreateUserAndAgency({
body: req.body,
}).then(r => {
res.json(r);
}).catch(e => {
console.debug(e);
res.status(e.error.status).json(e);
})
});
describe('User', async function() {
describe('#createUser()', async function() {
it('should return error 500 for unknown errors', async function(done) {
const req: any = { };
const res: any = {
status: (status: number) => {
assert.equal(status, 500);
console.log("TEST");
done();
},
json: (data: any) => {
console.log("TEST");
done();
}
};
fcts.createUserViaEmail(req, res);
});
});
});
错误日志:
> test
> mocha --require ts-node/register test/**/*.spec.ts
{"severity":"WARNING","message":"Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail"}
User
#createUser()
TypeError: Cannot read properties of undefined (reading 'user')
at onCreateUserAndAgency (C:\Users\Orionss\Projets\PATH\functions\src\users\on-create.ts:20:70)
... Many less specific error lines
{
error: {
status: 500,
message: "Une erreur inattendue s'est produite.",
date: 2021-12-21T14:04:42.842Z
}
}
1) should return error 500 for unknown errors
0 passing (2s)
1 failing
1) User
#createUser()
should return error 400 for missing info:
Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\Orionss\Projets\PATH\functions\test\main.spec.ts)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
【问题讨论】:
-
你也可以看看这个 SO thread
标签: typescript firebase google-cloud-functions mocha.js