node.js - mocha, mongoose - done() 多次调用
问题描述
我有用于测试用户注册的测试套件:
const chai = require('chai');
const chaiHttp = require('chai-http');
const { app } = require('../../');
const {User} = require('../../models/');
chai.use(chaiHttp);
describe('Register new user', () => {
it('it should register new user and return data', done => {
done();
chai.request(app)
.post('/api/users')
.send({name: 'Alex', email:'alex@gmail.com', password: 'alextest'})
.then(res => {
console.log('1-st done called');
done();
});
});
it('it should display not provided data error', done => {
chai.request(app)
.post('/api/users')
.send({})
.then(res => {
chai.expect(res).to.have.status(400);
chai.expect(res.body.errors).to.be.an('object');
chai.expect(res.body.errors).to.have.ownProperty('password');
chai.expect(res.body.errors).to.have.ownProperty('email');
chai.expect(res.body.errors).to.have.ownProperty('name');
done();
});
});
after(done => {
User.deleteMany({}, err => {
done();
});
});
});
每次我运行这个测试。有一个错误。如果我删除它('它应该显示未提供的数据错误')测试结果测试套件通过。但是在一个测试用例中使用这两个测试用例,一个总是失败。
Server running on port 3000
api_1 | Register new user
api_1 | ✓ it should register new user and return data
api_1 | 2-cnd done called
api_1 | ✓ it should display not provided data error
api_1 | 1-st done called
api_1 | 1) it should register new user and return data
api_1 | done delete many called
api_1 |
api_1 |
api_1 | 2 passing (121ms)
api_1 | 1 failing
api_1 |
api_1 | 1) Register new user
api_1 | it should register new user and return data:
api_1 | Error: done() called multiple times
api_1 | at /usr/src/app/test/it/auth.js:18:13
api_1 | at processTicksAndRejections (internal/process/task_queues.js:94:5)
无法弄清楚我做错了什么......
解决方案
您done
在此测试中调用了两次:
it('it should register new user and return data', done => {
done(); // <—- ONCE
chai.request(app)
.post('/api/users')
.send({name: 'Alex', email:'alex@gmail.com', password: 'alextest'})
.then(res => {
console.log('1-st done called');
done(); // <—- TWICE
});
});
删除第一个。
希望这可以帮助。
推荐阅读
- state - 高级关联规则挖掘
- python-3.x - 使用 Selenium 刮玻璃门
- javascript - 如何在 WebRTC 流中显示每个接收到的帧?
- redis - redis,设置一个值为3,但它的类型是字符串
- spring-boot - 高 CPU 使用率和 ActiveMQ Artemis 中许多队列和会话的负载
- vim - 在 Vim 中的每一行末尾添加一个反斜杠
- laravel - Git-win10-laragon-权限被拒绝
- asp.net-mvc - 如果在响应标头中同时传递 X-Frame-options SAMEORIGIN 和 DENY 会发生什么?
- excel - Excel VBA - 改进全局变量使用的技巧
- amazon-ec2 - 如何使用 ec2_sd_config 和 blackbox exporter 进行多目标和多端口服务状态检查。?