我一直在研究pact-js-mocha示例,当预期的响应是错误时,我在验证交互方面遇到了一些困难。这是我想验证的互动:
PactConsumer(PactOpts, function () {
addInteractions([{
state: 'i have a list of projects',
uponReceiving: 'a bad request for projects',
withRequest: {
method: 'get',
path: '/projects'
},
willRespondWith: {
status: 400,
headers: { 'Content-Type': 'application/json; charset=utf-8' },
body: { reply: 'this is a 400' }
}
}])
verify('a 400 is returned', expectError, function (result, done) {
expect(JSON.parse(result)).to.eql({ reply: 'this is a 400' })
})
finalizePact()
})
但是我不确定expectError()函数。在示例中,这将返回一个超级请求,但是当交互中的状态设置为400时,该方法似乎会抛出错误。
我已经尝试了一些东西,但它主要是跟踪并且都是错误的(比如使用supertest来创建请求并期待它的结果)。
感谢您的帮助
答案 0 :(得分:0)
可能的一项工作已经完成了我的工作:
const chai = require('chai');
const expect = require('chai').expect;
chai.use(require('chai-as-promised'));
var should = chai.should();
const request = require('superagent');
const commons = require('./specCommons');
const EXPECTED_BODY = {
"errors": [
"invalid request"
]
};
const SENT_BODY = {
"body": null
};
PactConsumer(commons.PACT_OPTS, function() {
addInteractions([{
state: 'the state',
uponReceiving: 'an invalid request,
withRequest: {
method: 'POST',
path: commons.PATH,
headers: commons.REQUEST_HEADERS,
body: SENT_BODY
},
willRespondWith: {
status: 400,
headers: commons.RESPONSE_HEADERS,
body: EXPECTED_BODY
}
}]);
function requestTemplate() {
return request.post('http://localhost:' + commons.PACT_OPTS.providerPort + commons.PATH)
.set(commons.REQUEST_HEADERS)
.send(SENT_BODY)
.catch((error) => {
return JSON.stringify(error);
});
}
verify('a 400 error is returned for an invalid request', requestTemplate,
function(result, done) {
result = JSON.parse(result);
Promise.all([
expect(result.response.text).to.equal(JSON.stringify(EXPECTED_BODY)),
expect(result.status).to.equal(400)
]).should.notify(done);
});
finalizePact();
});
specCommons.js的样子:
module.exports = {
PATH: 'api endpoint',
REQUEST_HEADERS: {
'Accept': 'application/json'
},
RESPONSE_HEADERS: {
'Content-Type': 'application/json; charset=utf-8'
},
PACT_OPTS: {
consumer: 'our consumer',
provider: 'our provider',
providerPort: 1234
}
};