我正在使用Jest和Supertest测试我的Express API。由于某些原因,这不起作用:
const id = await request.post('/program')
.send(body)
.expect('Content-Type', /json/)
.expect(201).body.id;
失败并显示错误:
TypeError: Cannot read property 'id' of undefined
154 | sessionId: defaults.authorId
155 | };
> 156 | const id = await request.post('/program')
| ^
157 | .send(body)
158 | .expect('Content-Type', /json/)
159 | .expect(201).body.id;
at Object.<anonymous> (tests/program.test.js:156:27)
但是,仅将.body.id
移动到下一行即可解决此问题。
const res = await request.post('/program')
.send(body)
.expect('Content-Type', /json/)
.expect(201);
const id = res.body.id;
为什么会这样?是否没有正确await
请求?
在第一种情况下,您正在从expect(201)
的返回值读取属性。