我有用于测试用户注册的测试套件:
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:'[email protected]', 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:'[email protected]', password: 'alextest'})
.then(res => {
console.log('1-st done called');
done(); // <—- TWICE
});
});
删除第一个。
希望这会有所帮助。