【问题标题】:Problem running Jest using CLS with async functions使用带有异步函数的 CLS 运行 Jest 时出现问题
【发布时间】:2020-08-24 03:27:20
【问题描述】:

我似乎无法让 CLS 与 Jest 一起工作。

以下代码:

export {}
const { promises: fs } = require('fs')

describe('CLS tests', () => {
  test('Can test CLS', async () => {
    var createNamespace = require('cls-hooked').createNamespace
    var session = createNamespace('session')
    session.run(async function () {
      await fs.readFile('package.json', 'utf-8')
      console.log('I cant log this')
    })
  })
})

导致以下错误:

测试完成后无法登录。你是否忘记等待某事 在你的测试中异步? 尝试记录“我无法记录”。

为什么我的测试似乎提前退出了?

【问题讨论】:

    标签: javascript async-await jestjs


    【解决方案1】:

    也许您需要抽象出asynchronous 操作。我在我的系统上试过这个,它可以工作。

    const {promises: fs} = require('fs')
    
    const runSession = () => new Promise((resolve, reject) => {
      const createNamespace = require('cls-hooked').createNamespace
      const session = createNamespace('session')
      session.run(() => {
        fs.readFile('package.json', 'utf-8')
            .then(resolve)
      })
    })
    
    describe('CLS tests', () => {
      test('Can test CLS', async () => {
        const result = await runSession()
        console.log('hello')
        console.log(result)
        expect(result).toBeTruthy()
        console.log('after expect...')
      })
    })
    
    

    祝你好运……

    【讨论】:

    • 最欢迎@JamieAlexander :) 。如果这回答了您的问题;请accept anwer 点击答案顶部附近左侧的勾号。
    猜你喜欢
    • 2021-01-30
    • 2011-11-20
    • 1970-01-01
    • 2021-12-18
    • 2019-03-13
    • 2019-03-28
    • 2022-11-10
    • 2019-06-15
    • 2020-11-25
    相关资源
    最近更新 更多