柴http - 双回调问题

时间:2017-07-03 06:35:25

标签: node.js mocha chai chai-http mockgoose

我使用chai-http对我的REST api进行了正常的单元测试。它失败并出现以下错误

warn: double callback!
error: { SyntaxError: Unexpected token { in JSON at position 58
    at Object.parse (native)
    at IncomingMessage.<anonymous> (E:\projects\node_modules\chai-http\node_modules\superagent\lib\node\parsers\json.js:8:35)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  rawResponse: '{"books":[],"count":0,"page":1,"pages":0,"pageSize":10}{"books":[],"count":0,"page":1,"pages":0,"pageSize":10}',
  statusCode: 200,
  response: undefined }

如您所见,由于测试失败,rawResponse重复。我调试了代码,控制器代码只调用一次,输出正确。但无法理解为什么会出现这种错误。

以下是测试代码

// some code to mock mongoose with mockgoose
....
....

let server = require('../../../server');
let should = chai.should();
chai.use(chaiHttp);


describe.only('Books', () => {
  describe('/GET book', () => {
      it('it should GET all the books', (done) => {
        chai.request(server)
            .get('/api/books')
            .end((err, res) => {
                console.log(res);
                res.should.have.status(200);

              done();
            }).catch(function(err){
                console.error(err);
                done(err);
            });
      });
  });
});

1 个答案:

答案 0 :(得分:7)

您混合了两种类型的异步处理:使用.end/.catch代替.then/.catch .end

因为出现错误,.end()(第一个参数err,set)和.catch()都被调用,导致done回调被调用两次

以下是使用.then/.catch的解决方案,结合Mocha的内置承诺支持(不使用done):

it('it should GET all the books', () => {
  return chai.request(server)
      .get("/api/books")
      .then(res => {
        console.log(res);
        res.should.have.status(200);
      })
      .catch(err => {
        console.error(err);
        throw err; // Re-throw the error if the test should fail when an error happens
      });
});

使用.end

it('it should GET all the books', done => {

  chai.request(server)
      .get("/api/books")
      .end((err, res) => {
        if (err) return done(err);
        console.log(res);
        res.should.have.status(200);
        done();
      });

});