【问题标题】:How to test key and value of object using supertest module如何使用 supertest 模块测试对象的键和值
【发布时间】:2020-06-26 11:09:44
【问题描述】:

我有如下测试代码:

const mocha = require('mocha');
const describe = mocha.describe;
const it = mocha.it;
const chai = require('chai');
const request = require('supertest');

const app = require('../app.test');

chai.should();

describe('Get /histories', () => {
  it('should return 200 status code', done => {
    request(app)
      .get('/client/profile')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });

  it('should return code: 400', done => {
    request(app)
      .get('/client/profile')
      .expect('Content-Type', /json/)
      .expect(200)
      .expect(res => {});
  });
});

我使用 Express 以自定义状态代码进行响应:

return res.json({
    code: 400
})

因此我想测试测试代码是否有代码作为对象的键,值是 400 作为数字。

我该如何编写这个测试?

【问题讨论】:

  • 您是否尝试在最后一个.expect 回调中使用response?
  • @jonrsharpe 不,我是单元测试员的新手。你能帮我写一些代码吗?
  • 不,SO 不是代码编写服务。查看 Supertest 文档,他们有响应断言的示例。

标签: javascript node.js express supertest


【解决方案1】:

你可以用这个:

it('should return code: 400', (done) => {
  request(app)
    .get('/client/profile')
    .expect('Content-Type', /json/)
    .expect(200)
    .end((err, res) => {
      if (err) {
        return done(err);
      }
      expect(res.code).to.be.equal(400);
      return done();
    });
});

【讨论】:

    【解决方案2】:

    我认为这就是您要寻找的。如果您需要更多信息,请告诉我。

    it('should return code: 400', async (done) => {
        var resp = await request(app)
          .get('/client/profile')
          expect(resp.statusCode).to.equal(400)
          expect(resp.body.code).to.equal(400)
      });
    

    resp.statusCode 是 http 响应代码。 resp.body 是响应正文。由于那是一个 json,响应 json 将有code

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多