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

NodeJs - Mongoose query in API failing in Mocha Chai test only

我是 Mocha/Chai 中单元测试的新手,一直在这个问题上卡住。我有一个 POST 用于注册新用户。在 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 中进行测试时不起作用,但在我通过 postman 连接时起作用。任何想法将不胜感激。

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 清理我的用户 table,因此 table 在第二次测试中为空。我已经更改了我的测试。

beforeEach(async() => {
    server = require('../index');
    await User.remove({});
});

再次感谢!