简体   繁体   English

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

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

I am trying to call a function from my app using supertest and sending a custom express request but I am getting a 422 Error when I send my request.我正在尝试使用 supertest 从我的应用程序调用一个函数并发送自定义快速请求,但是当我发送请求时出现 422 错误。

This is my custom express request这是我的自定义快递请求

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

This is my mock request这是我的模拟请求

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

This is my test so far这是我到目前为止的测试

 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})
                        })
                })

The message that is in the response is "body.groupName\" is required". How should I be creating the custom request?响应中的消息是“body.groupName\”是必需的”。我应该如何创建自定义请求?

Here's one of supertest 's examples:这是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();
      });
  });
});

Notice that in their send method, they directly send the body .请注意,在他们的send方法中,他们直接发送 body They don't extend or make their own Request .他们不会扩展或提出自己的Request

So to fix your issue you just need to send the body and not the fake 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