【问题标题】:How to test Promise catch with Mocha如何用 Mocha 测试 Promise catch
【发布时间】:2017-02-04 00:14:53
【问题描述】:

我正在尝试从请求模块测试 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 部分的代码。

【问题讨论】:

  • 例如,您可以在 url 中捕获带有无效协议的异常。尽管为规范存根fetch 会更有效。顺便说一句,代码是 promise 构造函数反模式,它可能只是 return fetch(...).then(...).catch(...)

标签: unit-testing promise ecmascript-6 mocha.js chai


【解决方案1】:

我最终编写了以下代码来测试捕获:

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();
        }
    );
});

【讨论】:

  • 如果任何断言失败(它们抛出错误),您将遇到此设置的问题。请参阅我今天早些时候发布的this answer
  • 如果断言失败,测试应该会中断,我认为这没有问题。无论如何,我认为您在链接答案中解释的方法似乎是一种更好的方法。
  • 我的回答是,如果断言失败,测试可能不会按预期中断。
猜你喜欢
  • 2013-02-10
  • 2017-04-08
  • 2015-02-17
  • 2015-07-16
  • 2016-06-19
  • 1970-01-01
  • 2017-10-07
  • 2015-12-01
  • 2014-12-21
相关资源
最近更新 更多