Is it possible to stub or mock httpcontext in unit test ?
Closed this issue · 4 comments
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
Hi there, I'm facing the exact same situation. Did anyone find kinda solution to this?
@RsknCankov not yet ...
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.
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);