skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
299 stars 26 forks source link

Is it possible to stub or mock httpcontext in unit test ? #44

Closed mshafiqmk closed 4 years ago

mshafiqmk commented 4 years ago

I have used express-http-context in node(express) which is working fine. But I want to write unit test for some methods where i have used httpContext , so while calling that method directly from unit test code the httpcontext is undefined.

Is there is any possible solution for that ?

Thanks

RsknCankov commented 4 years ago

Hi there, I'm facing the exact same situation. Did anyone find kinda solution to this?

mshafiqmk commented 4 years ago

@RsknCankov not yet ...

vuk-nikolic commented 4 years ago

With jest I was able to the following:

const httpContext = require("express-http-context");
jest.mock("express-http-context");

test("it should mock value in httpContext", function() {
      httpContext.get.mockImplementation(() => 42);
      const result = httpContext.get("someValue");
      expect(result).toBe(42);
})

Hope that helps. More info here https://jestjs.io/docs/en/mock-functions I'm pretty sure same can be done with mocha and other test frameworks.

RsknCankov commented 4 years ago

I am using ts-mockito and also succeeded in mocking it as follow:

import * as expresshttp from 'express-http-context'; when(spyExp.get('context')).thenReturn(JSON.stringify(product)); const spyExp = spy(expresshttp);