我是在Mocha / Chai进行单元测试的新手,并一直坚持这个问题。我有一个用于注册新用户的POST。在那篇文章中,我检查用户是否已经在数据库中。
if(error) return res.status(400).send(error.details[0].message);
console.log('check this ' + req.body.email);
//console.log(`Connected to ${db}...`)
console.log(`Connected to ${User.db.mongoose}...`)
let user = await User.findOne({ email: req.body.email});
console.log(user);
if(user) return res.status(400).send('User already registered');
我发现的第一个测试将注册用户(将信息插入数据库)。我发现第二次测试失败。
it('Should reject duplicate new user', async() => {
const res = await request(server)
.post('/api/users/')
.send({firstname: sFirstName, lastname: sLastName, email: sEmail, password: sPassword});
expect(res.status).to.be.equal(400);
expect(res.error).to.be.equal('User already registered');
});
失败的原因是查询失败的连接字符串,因此不返回任何记录。因此,我在Postman中测试了查询,并且POST API可以按预期工作。我很好奇是否有人知道为什么在Mocha中运行测试时猫鼬查询不起作用,但通过邮递员连接时却起作用。任何想法将不胜感激。
const {User, validate} = require('../models/user');
module.exports = function() {
//Database connection
const db = config.get('db');
mongoose.connect(db,{ useNewUrlParser: true })
.then(() => console.log(`Connected to ${db}...`))
.catch(err => console.error(`Could not connect to ${db}...`, err));
}
您能否添加一个连接到dB的代码段。您应该检查的另一件事是,是否为测试设置了不同的环境,例如尚未设置的测试dB]
谢谢大家。我发现了问题。我正在使用BeforeEach清理用户表,因此在第二次测试中该表为空。我已经更改了测试。
beforeEach(async() => {
server = require('../index');
await User.remove({});
});
再次感谢您!