【问题标题】:Jest - some tests fail on the first run, but pass on the second and third run开玩笑 - 一些测试在第一次运行时失败,但在第二次和第三次运行时通过
【发布时间】:2021-01-20 15:15:31
【问题描述】:

我在节点服务器中使用 jest 和 supertest npm 编写测试。

当我一起运行所有测试时,有些测试失败了:

在终端中选择只运行失败的测试,运行它们并通过。

现在,如果我在终端中选择再次运行所有测试,所有测试都会通过,但会显示以下错误:

观看用法:按 w 显示更多。(node:9484) UnhandledPromiseRejectionWarning

我使用beforeEach() 删除数据库并为每个测试创建相同的初始数据库。

这是setUpDb():

const setUpDb = async () => {
    await neo4jContext('MATCH (n) DETACH DELETE n')
    await usersRepository.addUser(user1)
    await usersRepository.addUser(user2)
    await productsRepository.addProduct({ userId: user1.id, product: product1 })
    await productsRepository.addProduct({ userId: user1.id, product: product2 })
    await storesRepository.addStore({
        userId: user1.id, store: store1, products: [product3]
    })
    await storesRepository.addStore({
        userId: user1.id, store: store2, products: [product3]
    })
}

//

beforeEach(setUpDb)

使用--runInBand 测试依次运行,一个接一个,所以不应该出现混淆状态。

这是 package.json 中的配置

"scripts": {
    "start": "node src/index.js",
    "debug": "env-cmd -f ./config/dev.env node inspect src/index.js",
    "dev": "env-cmd -f ./config/dev.env nodemon src/index.js",
    "test": "env-cmd -f ./config/test.env jest --watch --runInBand"
  },
  "jest": {
    "testEnvironment": "node",
    "testTimeout": 50000
  }

我尝试调查它,但我发现的只是影响共同状态的测试,因此单独运行时会出现不同的结果。 我不认为这是这里的问题,因为以上所有。

感谢任何伸出援手的人!

【问题讨论】:

    标签: javascript node.js testing jestjs supertest


    【解决方案1】:

    它发生是因为我有一个带有异步功能的测试,我没有在它执行之前放置等待:

    it('should do something', async () => {
    const asyncFunc = async () => console.log('async func needs await on exe')
    
    //wrong
    asyncFunc()
    //right
    await asyncFunc()
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-28
      • 2015-12-01
      • 2011-09-02
      • 1970-01-01
      • 2017-05-20
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多