突然我的测试无缘无故地失败了,但我的 API 正在工作

Suddenly my test is failing without any reason but my API is working

我休息了 1 小时玩电子游戏,当我回来时,一个测试失败了:'MongoClient must be connected to perform this operation'(操作是 insertOne)。问题是,我有多个使用 DB 的测试,它们都通过了,但是一个特定的测试不再通过,我最近甚至没有编辑这个文件。我在本地主机中使用 MongoDB 进行测试,在内存中使用 MongoDB。

在执行任何 commit/push 之前,我使用 husky 和 ​​lint-staged 来确保我的测试通过。除此之外,我还在做 TDD,所以我一直在测试。我什至恢复到我的项目的旧版本,并且所有版本都有这个特定的测试失败。怎么回事??

最奇怪的部分是:我的 API 工作正常,我的测试没有!

我的测试:

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)
  }
}

我的 API 正在工作:

但是我的测试不工作:

问题已解决...我将post 保留在这里,因为这是一个有趣的故事,哈哈。我恢复到一个旧版本,它在注册时没有发送电子邮件并且它有效。这让我相信邮件服务有问题,而不是 MongoDB,正如错误提示的那样(不知道为什么它一直说这是一个 mongodb 错误)。

发生的事情是:当我处于开发者模式时,电子邮件通过 mailtrap 发送,而当我不处于开发者模式时,它通过 sendgrid 发送。当我测试一些东西时,我进入测试模式,这不是开发者模式,所以它使用了 sendgrid。 Sendgrid 每天有 100 封电子邮件的限制(免费用户),我达到了他们的限制。这就是我收到错误的原因,但不知何故开玩笑说这是一个 mongodb 连接错误。