gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:26 25 4
gpt4 key购买 nike

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

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

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 编辑,因此测试成功完成...

...并且因为没有任何东西在等待或处理被拒绝的 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 返回一个被拒绝的 Promise,但是如果那个 Promise 没有返回或者 await-ed那么测试也将通过:

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

...但是如果被拒绝的 Promise 被返回或被 await 编辑,那么测试将失败:

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(...) 返回一个 Promise

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

关于javascript - 使用 Mocha & Chai 进行 REST API 测试 - 未处理的 promise 拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55541405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com