繁体   English   中英

如何创建自定义快速请求以使用 supertest 进行测试

[英]How to create a custom express request to test with supertest

我正在尝试使用 supertest 从我的应用程序调用一个函数并发送自定义快速请求,但是当我发送请求时出现 422 错误。

这是我的自定义快递请求

export interface CreateGroupRequest extends Request {
    body: {
        groupName: string;
        email: string;
        country: string;
    };

这是我的模拟请求

                var testCreateGroupRequest: CreateGroupRequest = {
                   body: {
                        groupName: testName,
                        email: email,
                        country: 'US',
                    }
                } as Request

这是我到目前为止的测试

 await supertest(app)
                .post("/login")
                .send(testLoginBody)
                .expect(200)
                .then((response) => {
                    sessionToken = response.body.token
                }).then(() => {
                    supertest(app)
                        .post("/create_group")
                        .set('X-JWT-Token', `${sessionToken}`)
                        .send(testCreateGroupRequest)
                        .then((response) => {
                             console.log({response})
                        })
                })

响应中的消息是“body.groupName\”是必需的”。我应该如何创建自定义请求?

这是supertest的示例之一:

describe('POST /users', function() {
  it('responds with json', function(done) {
    request(app)
      .post('/users')
      .send({name: 'john'})
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);
        return done();
      });
  });
});

请注意,在他们的send方法中,他们直接发送 body 他们不会扩展或提出自己的Request

因此,要解决您的问题,您只需要发送正文而不是虚假请求:

supertest(app)
    .post("/create_group")
    .set('X-JWT-Token', `${sessionToken}`)
    .send({
        groupName: testName,
        email: email,
        country: 'US',
    })
    .set('Accept', 'application/json') // Don't forget the header for JSON!
    .then(console.log) // Shortened

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM