解决 Jest 测试异步请求时不能关闭 sequelize 连接

  • Node.js
  • 梁凤波
  • 443
  • 3

遇到的问题

在给 node 项目做单元测试接口时,使用了 jest 测试,当运行 npm run test 时测试完毕后,进程一直不结束,且提示:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

解决方案

在 package.json 里面的script 命令里新增配置项:--forceExit

"scripts": {
  "test": "jest _tests  --runInBand --forceExit --colors"
},

--forceExit

官方解释:

Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. Note: This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use --detectOpenHandles to help track it down.

简单解释:jest 测试完毕后,强制退出。另外建议还需要加一个参数:—runInBand,可能运行了两个 Koa 实例导致了监听端口的冲突,所以我们需要让 Jest 按顺序执行。

欢迎评论
评论列表
avatar

test

测试

avatar

leo

学习了

avatar

ddd

大佬好厉害啊,求带

TOP