abonifacio / nestjs-request-context

Helper library for accesing request from singleton services
MIT License
65 stars 8 forks source link

RequestContext.currentContext.req is undefined #10

Open JuTiger-Lee opened 1 year ago

JuTiger-Lee commented 1 year ago

Hi When running the test code in the unit jest environment, the RequestContext.currentContext.req in req property remains undefined.

sebastian-xicay commented 1 year ago

You can use something like this

jest.mock('nestjs-request-context', () => ({ RequestContext: { currentContext: { req: { user: {}, }, }, }, }));

and then in test suite, just mock the currentContext.req to what you want

RequestContext.currentContext.req.user = ....;

It's my case with mocking user, but you can use it as you want

gregoryorton-ws commented 6 months ago

just mock the currentContext.req to what you want

@sebastian-xicay - how do you access this to mock it?

sebastian-xicay commented 6 months ago

just mock the currentContext.req to what you want

@sebastian-xicay - how do you access this to mock it?

I've attached the example

jest.mock('nestjs-request-context', () => ({
 RequestContext: {
  currentContext: {
   req: {
    user: {},
   },
  },
 },
}));
gregoryorton-ws commented 6 months ago

Oh. But you said 'and then in test suite, just mock the currentContext.req to what you want' - I assumed there was some future mocking beyond what you're saying here @sebastian-xicay

gregoryorton-ws commented 6 months ago

Anyway, I found my problem - it was caused by not have my extended prisma client used in my tests.