Superagent响应主体直到下一行都未定义

问题描述 投票:1回答:1

我正在使用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请求?

javascript node.js express jestjs superagent
1个回答
0
投票

在第一种情况下,您正在从expect(201)的返回值读取属性。

© www.soinside.com 2019 - 2024. All rights reserved.