简体   繁体   English

使用 Mocha 和 Chai 进行 REST API 测试-未处理的承诺拒绝

[英]REST API test with Mocha & Chai- Unhandled promise rejection

I made a very simple RESTful API that allows users to add, delete and update information about Hogwarts students.我制作了一个非常简单的 RESTful API,允许用户添加、删除和更新有关霍格沃茨学生的信息。 Mongo acts as the persistence layer. Mongo 充当持久层。

A GET request to url/students is supposed to return a list of all student objects.url/students GET 请求应该返回所有学生对象的列表。 While writing the test for it I wrote在为它编写测试时我写了

expect(res).to.equal('student list');

This is just for an initial check to make sure the test would fail but it isn't instead I get this error:这只是为了确保测试失败的初步检查,但它不是我收到此错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected { Object (domain, _events, ...) } to equal 'student list'

So it knows that the two values are different but instead of the test failing it's throwing an error.所以它知道这两个值是不同的,但它不是测试失败而是抛出错误。 I've pasted the full test code below.我在下面粘贴了完整的测试代码。

let chai = require('chai');
let chaiHttp = require('chai-http');
var MongoClient = require('mongodb').MongoClient;
chai.use(chaiHttp);
const expect = chai.expect;

describe('Students', async () => {
  describe('/GET students', () => {
    it('should GET all the students', async () => {
      chai.request('http://localhost:5000')
        .get('/students')
        .then(function (res) {
          try {
            expect(res).to.equal('hola');
          } catch (err) {
            throw err;
          }
        })
        .catch(err => {
          throw err; //this gets thrown
        })
    });
  });
});

And if you can show me the syntax of properly using async await for writing these tests please do that too.如果您可以向我展示正确使用 async await 编写这些测试的语法,请也这样做。

The test passes and logs the "Unhandled promise rejection" warning because the error is thrown within a Promise which just causes the Promise to reject.测试通过并记录"Unhandled promise rejection"警告,因为错误是在Promise中引发的,这只会导致Promise拒绝。

Since the Promise is not returned or await -ed, the test completes successfully...由于Promise没有返回或await -ed,测试成功完成...

...and because nothing is waiting for or handling the rejected Promise , Node.js logs a warning. ...并且因为没有任何东西在等待或处理被拒绝的Promise ,Node.js 会记录一个警告。

Details细节

An error thrown in a test will fail the test:测试中抛出的错误将使测试失败:

it('will fail', function () {
  throw new Error('the error');
});

...but a rejected Promise will not fail the test if it is not returned or await -ed: ...但是被拒绝的Promise如果没有返回或await -ed 不会使测试失败:

it('will pass with "Unhandled promise rejection."', function() {
  Promise.reject(new Error('the error'));
});

.catch returns a Promise so throwing in a .catch returns a rejected Promise , but if that Promise is not returned or await -ed then the test will also pass: .catch 返回一个Promise因此抛出.catch返回一个被拒绝的Promise ,但如果该Promise没有返回或await -ed 那么测试也将通过:

it('will also pass with "Unhandled promise rejection."', function() {
  Promise.reject(new Error('the error')).catch(err => { throw err });
});

...but if a rejected Promise is returned or await -ed then the test will fail: ...但如果返回一个被拒绝的Promiseawait -ed 那么测试将失败:

it('will fail', async function() {
  await Promise.reject(new Error('the error'));
});

And if you can show me the syntax of properly using async await for writing these tests please do that too.如果您可以向我展示正确使用 async await 编写这些测试的语法,请也这样做。

For your test you can simplify it to this:对于您的测试,您可以将其简化为:

const chai = require('chai');
const expect = chai.expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);

describe('Students', async function() {
  describe('/GET students', function() {
    it('should GET all the students', async function() {
      const res = await chai.request('http://localhost:5000').get('/students');
      expect(res).to.equal('hola');  // <= this will fail as expected
    });
  });
});

Details细节

From the chai-http doc :来自chai-http 文档

If Promise is available, request() becomes a Promise capable library如果Promise可用, request()将成为一个 Promise 能力库

...so chai.request(...).get(...) returns a Promise . ...所以chai.request(...).get(...)返回一个Promise

You can simply await the Promise and the test will wait until the Promise resolves before continuing.您可以简单地await Promise ,测试将等到Promise解决后再继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mocha、Chai 和 Sinon 未处理的承诺拒绝警告 - Unhandled promise rejection warning with Mocha, Chai and Sinon Mocha测试Http Request Promise是否抛出:未处理的Promise拒绝 - Mocha test if the Http Request Promise throw: Unhandled promise rejection Mocha&Chai-超过2000毫秒的超时。 确保在此测试中调用done()回调。“ - Mocha & Chai- “timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.” UnhandledPromiseRejectionWarning:未处理的承诺拒绝 - API - UnhandledPromiseRejectionWarning: Unhandled promise rejection - API UnhandledPromiseRejectionWarning:未处理的 API 承诺拒绝 - UnhandledPromiseRejectionWarning: Unhandled promise rejection for API 在Mocha中使用async / await - 测试挂起或以未处理的promise拒绝结束 - Usage of async/await in Mocha - test hangs or ends up with unhandled promise rejection 与摩卡咖啡和蔡测试,看诺言是否已解决或被拒绝 - Test with mocha and chai to see if a promise is resolved or rejected 当应用程序是 Promise 时开始 mocha chai 测试 - Start mocha chai test when app is a Promise 如何在未处理的 promise 拒绝中测试投掷 - How to test a throw in an unhandled promise rejection 与柴一起处理承诺拒绝 - Handle promise rejection with Chai
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM