-
Notifications
You must be signed in to change notification settings - Fork 834
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
test(responseInterceptor): add unit test
- Loading branch information
1 parent
a6f8e0d
commit 0fc013c
Showing
1 changed file
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import { IncomingMessage, ServerResponse } from 'http'; | ||
|
||
import { responseInterceptor } from '../../src/handlers/response-interceptor'; | ||
|
||
const fakeProxyResponse = () => { | ||
const httpIncomingMessage = new IncomingMessage(null); | ||
httpIncomingMessage._read = () => ({}); | ||
return httpIncomingMessage; | ||
}; | ||
|
||
const fakeResponse = () => { | ||
const httpIncomingMessage = fakeProxyResponse(); | ||
|
||
const response = new ServerResponse(httpIncomingMessage); | ||
response.setHeader = jest.fn(); | ||
response.write = jest.fn(); | ||
response.end = jest.fn(); | ||
|
||
return response; | ||
}; | ||
|
||
const waitInterceptorHandler = (ms = 1): Promise<void> => | ||
new Promise((resolve) => setTimeout(resolve, ms)); | ||
|
||
describe('responseInterceptor', () => { | ||
it('should write body on end proxy event', async () => { | ||
const httpIncomingMessage = fakeProxyResponse(); | ||
const response = fakeResponse(); | ||
|
||
responseInterceptor(async () => JSON.stringify({ someField: '' }))( | ||
httpIncomingMessage, | ||
null, | ||
response | ||
); | ||
|
||
httpIncomingMessage.emit('end'); | ||
await waitInterceptorHandler(); | ||
|
||
const expectedBody = JSON.stringify({ someField: '' }); | ||
expect(response.setHeader).toHaveBeenCalledWith('content-length', expectedBody.length); | ||
expect(response.write).toHaveBeenCalledWith(Buffer.from(expectedBody)); | ||
expect(response.end).toHaveBeenCalledWith(); | ||
}); | ||
|
||
it('should end with error when receive a proxy error event', async () => { | ||
const httpIncomingMessage = fakeProxyResponse(); | ||
const response = fakeResponse(); | ||
|
||
responseInterceptor(async () => JSON.stringify({ someField: '' }))( | ||
httpIncomingMessage, | ||
null, | ||
response | ||
); | ||
|
||
httpIncomingMessage.emit('error', new Error('some error meessage')); | ||
|
||
expect(response.setHeader).not.toHaveBeenCalled(); | ||
expect(response.write).not.toHaveBeenCalled(); | ||
expect(response.end).toHaveBeenCalledWith( | ||
'Error fetching proxied request: some error meessage' | ||
); | ||
}); | ||
}); |