简体   繁体   中英

Problem running Jest using CLS with async functions

I can't seem to get CLS to work with Jest.

The following code:

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

Results in the following error:

Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "I cant log this".

Why is it that my test appears to be exiting early?

Maybe you need to abstract out the asynchronous operations. I tried this on my system and it works.

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

在此处输入图片说明

Good Luck...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM