以下测试不适用于 mocha-chai,它能够获取输入请求,但会抛出错误消息。
it('/hb : ', function (done) {
return chai.request(app)
.post('/hb')
.send({"a":1 })
.then(function (res) {
expect(err).to.be.null;
expect(res).to.have.status(200);
// { ah: { rt: [Object] }, ad: { mojo: 1 } } }
//console.log("CAlling DOne ........... +");
done();
}, function (err) {
//console.log(err);
throw err;
});
});
输出:
Web Requests : /hb : : Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
最佳答案
chai-http
添加到 chai
的函数返回 promise 。在您的代码中,您返回了 promise ,这很好。但是,您还声明您的测试采用参数:function (done)
。如果您没有返回 Promise,这也没什么问题,但返回 Promise 确实是更好的机制。当您声明测试接受参数时,Mocha 会忽略测试的返回值,因此 Promise 会被忽略。因此,只需删除 done
的使用即可。
下面是一个示例,它重现了您在原始代码中遇到的错误,其中 err
在您传递给 then
的函数中未定义。
'use strict';
var app = require('./server');
var chai = require('chai');
chai.use(require('chai-http'));
var expect = chai.expect;
it('/hb', function () {
return chai.request(app)
.post('/hb')
.send({a: 1})
.then(function (res) {
expect(err).to.be.null;
expect(res).to.have.status(200);
});
});
如果服务器返回 200 状态,那么您将在控制台上看到以下内容:
1) /hb
0 passing (26ms)
1 failing
1) /hb:
ReferenceError: err is not defined
at test.js:13:20
如果服务器返回 400 状态,则输出将为:
1) /hb
0 passing (24ms)
1 failing
1) /hb:
Error: Bad Request
at Test.Request.callback (node_modules/superagent/lib/node/index.js:792:17)
at IncomingMessage.<anonymous> (node_modules/superagent/lib/node/index.js:990:12)
at endReadableNT (_stream_readable.js:913:12)
关于mocha.js - Mocha Chai HTTP post 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569551/