简体   繁体   中英

Why might my Mongoose connection close in-between calls?

So I have a test that tries to signup with the same email twice, at which point I am relying on Mongo's unique constraint to throw an error. If I run the query twice manually I get the correct error however, in my test I get a different error: "MongoError: server is closed" when the second call tries to run .save on that instance of the User model. I am using Node.js, Express, Mongoose and Mocha.

I have a beforeEach function that drops the collection and rebuilds the index before each test but I have put a console log in that proves it's not running in-between model calls, only once at the start as expected. So why might my connection be closing? I seen some blogs suggesting I up the pool size but I tried that and it made no difference:/

My test code...

// Check no email dupes is being enforced
it("should throw when we try to add user with dupe email", () => {
    assert.throws(async () => {
        await User.addNewUser({
            name: "Mandy  ",
            email: "  Mandy@iscool.com",
            password: "password",
        })
        await User.addNewUser({
            name: "Mandy  ",
            email: "  Mandy@iscool.com",
            password: "password",
        })
    })
})

My model code...

userSchema.statics.addNewUser = async function (params) {
    const randomSlug = cryptoRandomString({length: 64,  type: "url-safe"})
    const hashedPassword = await bcrypt.hash(params.password, 10)
    const user = new User({
        name: params.name,
        email: params.email,
        password: hashedPassword,
        active: false,
        activationCode: randomSlug
    })
    await user.save()
    return randomSlug
}

assert.throws is for asserting that errors are synchronously thrown from a function. Use assert.rejects to detect an asynchronous function returning a Promise that is rejected:

it("should throw when we try to add user with dupe email", async () => {
  await assert.rejects(async () => {
    await User.addNewUser({
      name: "Mandy  ",
      email: "  Mandy@iscool.com",
      password: "password",
    })
    await User.addNewUser({
      name: "Mandy  ",
      email: "  Mandy@iscool.com",
      password: "password",
    })
  })
})

What is probably happening to you is that assert.rejects runs your async function but just gets back a Promise; then the test passes because it's not waiting for the async stuff to complete, and your test suite is likely closing the connection. Then, after that first await completes, the connection is closed, and your second addNewUser fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM