[Question] Unit test an Express middleware using cls-hooked
xballoy opened this issue · comments
Hello,
I'm trying to write a unit test to check if the value I set is well setted in my middleware.
A simplified version (the namespace 'mynamespace' is already created) of my middleware is:
module.exports = (req, res, next) => {
ns.bindEmitter(req);
ns.bindEmitter(res);
ns.run(() => {
const correlationId = uuidV4();
getNamespace('mynamespace').set('correlationId', correlationId);
next();
});
};
My failing test is:
it.only('should set a correlationId in the uuid format in the request and the response', done => {
const req = new Emitter();
const res = new Emitter();
const next = sinon.stub();
correlationIdMiddleware(ns)(req, res, next);
ns.run(() => {
const correlationId = ns.get('correlationId');
correlationId.should.satisfy(isUUID.v4);
done();
});
});
It says that correlationId
is undefined
. My guess is that correlationId
doesn't exist anymore when I check it in my unit test.
When I run my application I can see my middleware working.
Any idea? Thanks!
It's hard to say without knowing what correlationIdMiddleware
does but it looks like the context only lives during the execution of correlationIdMiddleware
.
Take a look at cls-middleware and cls-hooked-sample to get an idea of the context's lifecycle in middleware and ways to test it.
Thanks. I'll have a look!
@xballoy did you resolve the issue? What is the solution?
In case anyone runs into this, this works for me:
import { ns } from '../auth/request-context';
describe('a test', () => {
let context;
beforeEach(() => {
context = ns.createContext();
ns.enter(context);
});
it('should store and retrieve a value', () => {
ns.set('key', 'value');
const response = ns.get('key');
response.should.equal('value');
});
afterEach(() => {
ns.exit(context);
});
});