Papooch / nestjs-cls

A continuation-local storage (async context) module compatible with NestJS's dependency injection.
https://papooch.github.io/nestjs-cls/
MIT License
393 stars 23 forks source link

Can't use clsService across different test runs with `--runInBand` #49

Closed lazaroofarrill closed 1 year ago

lazaroofarrill commented 1 year ago

I'm using a common setup function for all my unit tests. However when running several test suites together only the first one to use the ClsService succeeds. Repro url: https://github.com/lazaroofarrill/nestjs-cls-error-across-multiple-test-runs

Papooch commented 1 year ago

Hm, I was able to reproduce it. I suspect there's something strange happening with how Jest treats async_hooks, because the error only happens with the --runInBand flag set. Without it, it works okay.

It also seems it's not related to your common setup, as it reliably fails even without it.

Given you're only concerned with unit tests that don't need to run in band, this should be enough of a "workaround" for you, but I'll investigate further.

Papooch commented 1 year ago

It's most likely related to this bug in Jest that was closed with the following:

For anyone else who comes across this issue, if you want to have some automatic ALS setup for each test, beforeEach is probably a non-starter for now. More resilient approaches might be to 1. enterWith at the start of each test, or 2. roll your own test function that wraps your test in an ALS run.

Which is what I would also suggest.

The fact that the enterWith method is still not stable does not help the case.


To summarize:

lazaroofarrill commented 1 year ago

This is truly I sad. I was using a custom it function to wrap run but I really wanted to avoid that. I have to run the tests in band otherwise they crash my computer.

Papooch commented 1 year ago

I mean, in unit tests, you should treat ClsService as an external dependency and mock it out anyway. E2E tests should also work fine, since the request goes through the middleware. If need be, a custom it function seems like a viable workaround.

I have to close this though, because there's nothing I can do about it. Maybe try mocha as your test runner?