Node.js + Chai / Mocha /应该:针对相同的响应运行多个测试

时间:2014-11-24 01:24:46

标签: javascript node.js mocha chai should.js

我正在使用与以下内容非常类似的东西来使用Mocha执行一系列API测试。这很棒,但它需要为每个测试单独调用API。 我想使用相同的API调用并针对该响应运行多个测试。我一直在阅读您可以使用before来执行此操作,但实际上网络上没有任何示例显示它使用API​​调用?

var chai = require('chai');
var request = require('request');
var async = require('async');
var assert = chai.assert,
    expect = chai.expect,
    should = chai.should();

describe('/', function () {
  it('should return 200', function (done) {
    request.get('http://localhost:8000', function (err, res, body) {
      res.should.have.status(200);
      done();
    });
  });

  it('should say "Hello, world!"', function (done) {
    request.get('http://localhost:8000', function (err, res, body) {
      body.should.have.property('type', 'aType');
      done();
    });
  });
});

1 个答案:

答案 0 :(得分:5)

您可以使用before函数执行此操作,如此...

var chai = require('chai');
var request = require('request');
var async = require('async');
var assert = chai.assert,
    expect = chai.expect,
    should = chai.should();

describe('/', function () {
  var firstRequest;

  before(function(done) {
    request.get('http://localhost:8000', function(err, res, body) {
      firstRequest = {
        err:err,
        res:res,
        body:body
      };
      done();
    });
  });

  it('should return 200', function (done) {
    firstRequest.res.should.have.status(200);
    done();
  });

  it('should say "Hello, world!"', function (done) {
    firstRequest.body.should.have.property('type','aType');
    done();
  });
});

然而,除非你有充分的理由这样做,否则我认为你只需要合并测试就可以了。

var chai = require('chai');
var request = require('request');
var async = require('async');
var assert = chai.assert,
    expect = chai.expect,
    should = chai.should();

describe('/', function () {
  it('should return 200 and say "Hello, world!"', function (done) {
    request.get('http://localhost:8000', function (err, res, body) {
      res.should.have.status(200);
      body.should.have.property('type', 'aType');
      done();
    });
  });
});

如果测试失败,即使有两个断言,Mocha也会报告失败的具体原因。