I am faced with a challenge in my class where I need to mock an object along with its properties
intercept(context: ExecutionContext) {
const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked
if (response.headersSent) { // testing this scenario
return true
}
return false
}
When I simulate the dependency using a regular object literal and some anonymous functions, everything runs smoothly as anticipated
const executionContext = {
switchToHttp: () => executionContext, // simulates 'this' chaining
getRequest: () => {
return {
url: undefined,
method: undefined,
headers: undefined,
connection: {
remoteAddress: undefined,
remotePort: undefined
}
}
},
getResponse: () => {
return {
headersSent: true, // desire an easy way to alter this during testing without resorting to a factory
append: () => undefined
}
}
} as unknown as ExecutionContext
it('test', () => {
const response = myclass.intercept(executionContext);
expect(response).toBeTrue()
});
However, when I attempt to mimic some of the properties using jest.fn()
, unexpected outcomes surface.
const getResponseSpy = jest.fn(() => {
return {
headersSent: false,
append: () => undefined
}
});
const executionContext = {
switchToHttp: () => executionContext,
getRequest: () => {
return {
url: undefined,
method: undefined,
headers: undefined,
connection: {
remoteAddress: undefined,
remotePort: undefined
}
}
},
getResponse: getResponseSpy // provides a more convenient way to modify this
} as unknown as ExecutionContext
At this stage in my code, the response turns out to be undefined
TypeError: Cannot read property 'headersSent' of undefined
Moreover, if I try something like
getResponse: () => getResponseSpy
, then the response
within my code becomes a Jest mock object instead of the mimicked implementation, lacking the headersSent
property.
I sense that I might be overlooking a fundamental aspect. I attempted utilizing
switchToHttp: jest.fn().mockResturnThis()
Nevertheless, no alterations occur. It appears that the jest spy inside the object fails to provide its simulated implementation
What could be the issue here?