I am trying to write a unit test for a function that takes IncomingMessage as a parameter. I understand it is a stream but I am unsure how to create a basic test dummy as the stream causes my tests to timeout
: Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
My class
import { IncomingMessage } from 'http';
export class MyClass
example(request: IncomingMessage): void {
console.log(request.get('hello?'))
}
}
My test
it('test', () => {
const myclass = new MyClass();
const request = {
get: () => 'hello!'
} as unknown as IncomingMessage
const response = myclass.example(request);
expect(response).toEqual('hello!');
});
I assume I need to close the stream so how can I do that when casting a 'dummy' object to type IncomingMessage?
I tried using
const request = {
get: () => 'hello'
} as unknown as IncomingMessage
request.setTimeout(1)
but then I get an error that the function is not found, which makes sense since the dummy is basically an empty object with only one mocked function
TypeError: request.setTimeout is not a function
In this case I assume I need to actually create a real IncomingMessage? But I cannot find much documentation or examples on how to do this
What is the best way to create a real IncomingMessage stream, close it quickly and have a mocked get method? I think I would then need to mock a socket?
Or what is the correct way to test my class and function in this case?
