|
| 1 | +import { ClientRequest } from 'http'; |
| 2 | +import * as querystring from 'querystring'; |
| 3 | + |
| 4 | +import { fixRequestBody } from '../../src/handlers/fix-request-body'; |
| 5 | +import type { Request } from '../../src/types'; |
| 6 | + |
| 7 | +const fakeProxyRequest = () => { |
| 8 | + const proxyRequest = new ClientRequest('http://some-host'); |
| 9 | + proxyRequest.emit = jest.fn(); |
| 10 | + |
| 11 | + return proxyRequest; |
| 12 | +}; |
| 13 | + |
| 14 | +describe('fixRequestBody', () => { |
| 15 | + it('should not write when body is undefined', () => { |
| 16 | + const proxyRequest = fakeProxyRequest(); |
| 17 | + |
| 18 | + jest.spyOn(proxyRequest, 'setHeader'); |
| 19 | + jest.spyOn(proxyRequest, 'write'); |
| 20 | + |
| 21 | + fixRequestBody(proxyRequest, { body: undefined } as Request); |
| 22 | + |
| 23 | + expect(proxyRequest.setHeader).not.toHaveBeenCalled(); |
| 24 | + expect(proxyRequest.write).not.toHaveBeenCalled(); |
| 25 | + }); |
| 26 | + |
| 27 | + it('should not write when body is empty', () => { |
| 28 | + const proxyRequest = fakeProxyRequest(); |
| 29 | + |
| 30 | + jest.spyOn(proxyRequest, 'setHeader'); |
| 31 | + jest.spyOn(proxyRequest, 'write'); |
| 32 | + |
| 33 | + fixRequestBody(proxyRequest, { body: {} } as Request); |
| 34 | + |
| 35 | + expect(proxyRequest.setHeader).not.toHaveBeenCalled(); |
| 36 | + expect(proxyRequest.write).not.toHaveBeenCalled(); |
| 37 | + }); |
| 38 | + |
| 39 | + it('should write when body is not empty and Content-Type is application/json', () => { |
| 40 | + const proxyRequest = fakeProxyRequest(); |
| 41 | + proxyRequest.setHeader('content-type', 'application/json; charset=utf-8'); |
| 42 | + |
| 43 | + jest.spyOn(proxyRequest, 'setHeader'); |
| 44 | + jest.spyOn(proxyRequest, 'write'); |
| 45 | + |
| 46 | + fixRequestBody(proxyRequest, { body: { someField: 'some value' } } as Request); |
| 47 | + |
| 48 | + const expectedBody = JSON.stringify({ someField: 'some value' }); |
| 49 | + expect(proxyRequest.setHeader).toHaveBeenCalledWith('Content-Length', expectedBody.length); |
| 50 | + expect(proxyRequest.write).toHaveBeenCalledWith(expectedBody); |
| 51 | + }); |
| 52 | + |
| 53 | + it('should write when body is not empty and Content-Type is application/x-www-form-urlencoded', () => { |
| 54 | + const proxyRequest = fakeProxyRequest(); |
| 55 | + proxyRequest.setHeader('content-type', 'application/x-www-form-urlencoded'); |
| 56 | + |
| 57 | + jest.spyOn(proxyRequest, 'setHeader'); |
| 58 | + jest.spyOn(proxyRequest, 'write'); |
| 59 | + |
| 60 | + fixRequestBody(proxyRequest, { body: { someField: 'some value' } } as Request); |
| 61 | + |
| 62 | + const expectedBody = querystring.stringify({ someField: 'some value' }); |
| 63 | + expect(proxyRequest.setHeader).toHaveBeenCalledWith('Content-Length', expectedBody.length); |
| 64 | + expect(proxyRequest.write).toHaveBeenCalledWith(expectedBody); |
| 65 | + }); |
| 66 | +}); |
0 commit comments