NodeJs-API中的Mongoose查询仅在Mocha Chai测试中失败



我是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');
});

失败的原因是Query的连接字符串失败,因此没有返回任何记录。因此,我在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({});
});

再次感谢!

最新更新