ChaiJS:不能导致测试失败

时间:2015-04-02 13:07:37

标签: javascript mocha chai

我试图让我的第二个规格失败,但它不会失败。我从我的服务器返回statusCode 203,测试将其作为203接收,但由于某种原因,expect块仍然不会引发错误。这是怎么回事?

spec.js

var chai = require('chai');
var expect = chai.expect;
var request = require('request');
var localServerUri = 'http://127.0.0.1:3000/';

describe('server http routing', function(done){
  it('should receive a status code 200 after GET request', function() {
    request(localServerUri + 'pull', function (error, response, body) {
      expect(response.statusCode).to.be.at(200);
      done();
    });
  });

  it('should receive a status code 201 after POST request', function() {
    request.post({url:localServerUri + 'push', form: {key:'value'}}, function(err, response, body) { 
      //why wont this fail?
      console.log(response.statusCode === 201);
      expect(response.statusCode === 201).to.be.true;
      done();
    });
  });
});

app.js     var express = require(' express');     var app = express();

app.get('/pull', function (req, res) {
  res.send('works');
});

app.post('/push', function(req, res) {
  res.status(203);
  res.send('works');
});

var server = app.listen(3000, function () {

  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at port', host, port);

});

2 个答案:

答案 0 :(得分:0)

您需要将done传递到it块,而不是describe

var chai = require('chai');
var expect = chai.expect;
var request = require('request');
var localServerUri = 'http://127.0.0.1:3000/';

describe('server http routing', function(){
  it('should receive a status code 200 after GET request', function(done) {
    request(localServerUri + 'pull', function (error, response, body) {
      expect(response.statusCode).to.be.at(200);
      done();
    });
  });

  it('should receive a status code 201 after POST request', function(done) {
    request.post({url:localServerUri + 'push', form: {key:'value'}}, function(err, response, body) { 
      expect(true).to.be.true;
      done();
    });
  });
});

答案 1 :(得分:0)

这很简单。您传递给it两个来电的回调应该是function (done) {...而不是function () {...。现在,Mocha认为这些测试是同步的,所以它不会等待它们完成。

您传递给describe的回调需要done参数,但这没用。