Jeff-Lewis / cls-hooked

cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+
BSD 2-Clause "Simplified" License
759 stars 89 forks source link

[Question] Unit test an Express middleware using cls-hooked #17

Closed xballoy closed 3 years ago

xballoy commented 6 years ago

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!

Jeff-Lewis commented 6 years ago

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.

xballoy commented 6 years ago

Thanks. I'll have a look!

maldimirov commented 5 years ago

@xballoy did you resolve the issue? What is the solution?

xballoy commented 5 years ago

I never managed to make it works, sorry...

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐ On Tuesday, February 12, 2019 5:51 AM, Marin Aldimirov notifications@github.com wrote:

@xballoy did you resolve the issue? What is the solution?

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

krotscheck commented 5 years ago

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