【问题标题】:NodeJs - Mongoose query in API failing in Mocha Chai test onlyNodeJs - API 中的 Mongoose 查询仅在 Mocha Chai 测试中失败
【发布时间】:2020-02-20 07:16:54
【问题描述】:

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

}

【问题讨论】:

    标签: node.js mongodb mongoose mocha.js chai


    【解决方案1】:

    谢谢大家。我发现了这个问题。我正在使用 BeforeEach 清理我的用户表,因此该表在第二次测试中是空的。我改变了我的测试。

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

    再次感谢您!

    【讨论】:

      【解决方案2】:

      您能否添加一个连接到 dB 的位置的 sn-p。您应该检查的另一件事是您是否为您的测试设置了不同的环境,例如您尚未设置的测试分贝

      【讨论】:

      • 感谢您的回复。我在运行测试时正在使用测试环境。我需要调用几个中间件函数的 index.js,1 是 database.js 我感到困惑的部分是,当调用 user.save 并写入我的测试数据库但 User.findOne 不起作用时,该帖子适用于 1 测试。
      • 检查测试数据库是否已设置,Mongodb Uri 是否对测试数据库正确
      • Mcdavid,测试正在写入测试数据库并存储信息。唯一的问题是运行测试时 mongoose 查询不起作用,但它在 postmon 上运行。
      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      相关资源
      最近更新 更多