簡體   English   中英

如何使用Mocha測試Promise catch

[英]How to test Promise catch with Mocha

我正在嘗試從請求模塊測試GET HTTP方法:

const get = (host, resource, options) => {
  ...
  return new Promise((resolve, reject) => fetch(url, opts)
    .then(response => {
      if (response.status >= 400) {
        reject({ 
        message: `[API request error] response status: ${response.status}`, 
        status: response.status });
      }
      resolve(response.json());
    })
    .catch(error => reject(error)));
};

以下是我測試.then部分的方法:

it('Wrong request should return a 400 error ', (done) => {
    let options = { <parameter>: <wrong value> };
    let errorJsonResponse = {
    message: '[API request error] response status: 400',
    status: 400,
};
let result = {};

result = get(params.hosts.api, endPoints.PRODUCTS, options);

result
  .then(function (data) {
      should.fail();
      done();
    },

    function (error) {
      expect(error).to.not.be.null;
      expect(error).to.not.be.undefined;
      expect(error).to.be.json;
      expect(error).to.be.jsonSchema(errorJsonResponse);
      done();
    }
  );
});

但是我沒有找到測試catch部分的方法(當它給出錯誤並且響應狀態不是> = 400時)。

有什么建議?

它還可以幫助我解決問題一個簡單的例子,另一個代碼測試Promise的catch部分。

我最后編寫了以下代碼來測試catch:

it('Should return an error with invalid protocol', (done) => {
    const host = 'foo://<host>';
    const errorMessage = 'only http(s) protocols are supported';
    let result = {};

    result = get(host, endPoints.PRODUCTS);

    result
      .then(
        () => {
          should.fail();
          done();
        },

        (error) => {
          expect(error).to.not.be.null;
          expect(error).to.not.be.undefined;
          expect(error.message).to.equal(errorMessage);
          done();
        }
    );
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM