Problem running Jest using CLS with async functions

Viewed 148

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?

1 Answers

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

enter image description here

Good Luck...

Related