Home > Enterprise >  Suddenly my test is failing without any reason but my API is working
Suddenly my test is failing without any reason but my API is working

Time:09-28

I took a 1 hour long break to play some videogame and when I came back, one test was failing: 'MongoClient must be connected to perform this operation' (The operation is insertOne). The thing is, I have multiple tests that use DB and they are all passing, however a specific test is not passing anymore and I didn't even edit this file recently. I am testing using MongoDB in localhost with MongoDB in Memory.

I use husky and lint-staged to make sure my tests are passing before I do any commit/push. Besides that I am doing TDD, so I am constantly testing. I even restored to older versions of my project and all versions have this specific test failing. Wtf is going on??

The weirdest part is: my API is working just fine, my test don't!!

My test:

describe('POST /signup', () => {
  let userCollection: Collection

  beforeAll(async () => {
    await MongoHelper.connect(global.__MONGO_URI__)

    userCollection = MongoHelper.getCollection('users')

    app.post('/api/auth/signup', signUpController)
  })

  afterAll(async () => {
    await MongoHelper.disconnect()
  })

  afterEach(async () => {
    await userCollection.deleteMany({})
  })

  const agent = request.agent(app)

  it('Should return 200 if all validations succeds', async () => {
    await agent.post('/api/auth/signup').send(makeFakeSignUpUserCredentials()).expect(200)
  })
})

MongoHelper:

export const MongoHelper = {
  client: MongoClient,
  async connect (url: string): Promise<void> {
    this.client = await MongoClient.connect(url)
  },

  async disconnect (): Promise<void> {
    await this.client.close()
  },

  getCollection (name: Collections): Collection {
    return this.client.db().collection(name)
  }
}

My API is working: enter image description here

But my test is not working: enter image description here

CodePudding user response:

Problem was solved... I'll keep this post here because it is a funny story lol. I restored to an older version which did not send email upon signup and it worked. That made me believe that something was wrong with the mailer service and not MongoDB, as the error suggests (no idea why it kept saying it was a mongodb error).

What happened was: When I'm in developer mode, emails are send through mailtrap and when I am not, it send through sendgrid. When I test something, I get into test mode, which is not developer mode, so it used sendgrid. Sendgrid has a limit of 100 emails per day (free user) and I reached their limit. That's why I was getting the error, but somehow jest said it was a mongodb connection error.

  • Related