【问题标题】:Jest testing async function - Jest did not exit one second after the test run has completedJest 测试异步功能 - 测试运行完成后一秒钟 Jest 没有退出
【发布时间】:2021-06-16 10:25:15
【问题描述】:

我想通过 Jest 使用 node-mocks-http 测试我的 Next.js API 函数。 这是我要测试的功能:

export default async (
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> => {
  const foods = await getFoods()
  res.json(foods)
}

这是我的测试文件的样子:

import { createMocks } from 'node-mocks-http'
import handler from './foods'

  test('api route', async (done) => {
    try{
      const { req, res } = createMocks({
        method: 'GET',
      })
      await handler(req, res)
      expect(res._getStatusCode()).toBe(200)
      done()
    } catch(err){
      done(err)
    }
  })

如果没有await getFoods() 调用,一切都会按预期进行。但是,通过调用我得到错误:Jest did not exit one second after the test run has completed. getFoods() 是一个异步棱镜数据库查询。 这里缺少什么?

【问题讨论】:

    标签: javascript node.js jestjs next.js node-mocks-http


    【解决方案1】:

    不要混合使用done() 和异步代码,你不需要catch 块,如果async 函数拒绝,测试将失败。

    import { createMocks } from 'node-mocks-http'
    import handler from './foods'
    
      test('api route', async () => {
          const { req, res } = createMocks({
            method: 'GET',
          })
    
          await handler(req, res)
    
          expect(res._getStatusCode()).toBe(200)
      })
    

    【讨论】:

    • 使用这个我得到相同的“测试运行完成后一秒钟没有退出”错误
    【解决方案2】:

    您似乎有同步问题,因此您应该检查https://jestjs.io/es-ES/docs/25.x/tutorial-async,并且总是有典型的计时器解决方案,以防您的处理程序功能无法正常工作,您可以尝试这样的事情

    test('api route', async (done) => {
    try{
      const { req, res } = createMocks({
        method: 'GET',
      })
      await handler(req, res)
      setTimeout(() => {
        expect(res._getStatusCode()).toBe(200)
        done()
      }, 1000);
    } catch(err){
      done(err)
    }
    

    })

    【讨论】:

      【解决方案3】:

      如果我将它添加到我的测试文件中,这个警告就会消失:

      afterAll(async () => {
        await prisma.$disconnect()
      })
      

      【讨论】:

        猜你喜欢
        • 2018-12-08
        • 2021-03-28
        • 2019-02-05
        • 2023-03-13
        • 2019-06-15
        • 2019-09-16
        • 2019-05-24
        • 2020-08-26
        • 1970-01-01
        相关资源
        最近更新 更多