0

我一直在研究 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 创建一个请求并期待它的结果)。

谢谢你的帮助

4

1 回答 1

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
  }
};
于 2017-05-09T09:11:58.220 回答