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

REST API test with Mocha & Chai- Unhandled promise rejection

我做了一个非常简单的RESTfulAPI,允许用户添加、删除和更新有关霍格沃茨学生的信息。 Mongo 作为持久层。

url/students 的 GET 请求应该 return 所有学生对象的列表。在为其编写测试时,我写了

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

这只是为了进行初始检查以确保测试会失败,但实际上并没有,我得到了这个错误:

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

所以它知道这两个值是不同的,但不是测试失败而是抛出错误。 我在下面粘贴了完整的测试代码。

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

如果你能告诉我正确使用 async await 编写这些测试的语法,请也这样做。

测试通过并记录了 "Unhandled promise rejection" 警告,因为错误是在 Promise 中引发的,这只会导致 Promise 被拒绝。

由于 Promise 未返回或 await-ed,测试成功完成...

...因为没有任何东西在等待或处理被拒绝的 Promise,Node.js 记录警告。

详情

测试中抛出的错误将使测试失败:

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

...但是被拒绝的 Promise 如果没有返回或 await-ed:

将不会通过测试
it('will pass with "Unhandled promise rejection."', function() {
  Promise.reject(new Error('the error'));
});

.catch returns a Promise 所以抛出一个 .catch returns 一个被拒绝的 Promise,但是如果那个 Promise 没有返回或者 await-ed 那么测试也将通过:

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

...但是如果返回被拒绝的 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.

对于您的测试,您可以将其简化为:

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

详情

来自chai-http doc:

If Promise is available, request() becomes a Promise capable library

...所以 chai.request(...).get(...) returns 一个 Promise.

您可以简单地 await Promise,测试将等到 Promise 解决后再继续。