摩卡:单个服务器请求中的多个“it”调用

Mocha: Multiple "it" calls in single server request

本文关键字:it 调用 单个 服务器 请求 摩卡      更新时间:2023-09-26

我正在尝试使用 Mocha 测试 40+ API 端点。我想执行一些子测试作为单个服务器调用的一部分。

例如,我想测试是否it('returns valid JSON...it('returns a valid status code...等。

configs.forEach(function(config) {
    describe(config.endpoint, () => {
        it('...', function(done) {
            server
                .post(config.endpoint)
                .send({})
                .expect('Content-type', /json/)
                .expect(200)
                .end(function(err, res) {
                    //it('has a proper status code', () => {
                    expect(res.status).toEqual(200);
                    //})
                    //it('does not have an error object', () => {
                    expect(res.body.hasOwnProperty('error')).toEqual(false);
                    //})
                    done();
                })
        })
    })
})

问题是我无法嵌套it语句,但我依靠回调,通过done()来指示何时收到响应,所以我必须将调用包装在一个it语句中......

因为其中一些请求需要半秒才能解决,而且有 40+ 个,所以我不想为这些请求创建单独的测试。创建单独的测试也会复制 config.endpoint,我想看看每个端点的测试是否都在一个地方传递。

如何为单个服务器调用创建多个测试?

以下是我如何使用摩卡、柴和超级测试(API 请求)完成此操作:

import { expect } from "chai"
const supertest = require("supertest");
const BASE_URL = process.env.API_BASE_URL || "https://my.api.com/";
let api = supertest(BASE_URL);
describe("Here is a set of tests that wait for an API response before running.", function() {
  //Define error & response in the 'describe' scope. 
  let error, response;
  //Async stuff happens in the before statement.
  before(function(done) {
    api.get("/dishes").end(function(err, resp) {
      error = err, response = resp;
      done();
    });
  });
  it("should return a success message", function() {
    console.log("I have access to the response & error objects here!", response, error);
    expect(response.statusCode).to.equal(200);
  });
  it("should return an array of foos", function() {
    expect(response.body.data.foo).to.be.an("array");
  });
});
    configs.forEach(function(config) {
        describe(config.endpoint, () => {
            var response;    
            it('...', function(done) {
                server
                    .post(config.endpoint)
                    .send({})
                    .expect('Content-type', /json/)
                    .expect(200)
                    .end(function(err, res) {
                          response=res;
                          done();  
                      })
             });
                    it('has a proper status code', () => {
                          expect(response.status).toEqual(200);
                    })
                    it('does not have an error object', () => {
                            expect(response.body.hasOwnProperty('error')).toEqual(false);
                    })
         })
})

这个呢?我不确定测试用例的嵌套,但它对您有用。