So I created an extention on Express to handle XML, since the application I interface with uses XML still.
const XMLResponseHandler = (
req: Request,
res: Response,
next: NextFunction,
) => {
res.xml = (body) => res.set('Content-Type', 'application/xml').send(builder.buildObject(body));
console.log('oogabooga'); //pay attention to this log
next();
};
declare namespace Express {
interface Response {
xml: (body: unknown) => Response;
}
}
This is the way it's implemented in the controller
const getOrder = async (req: Request, res: Response) => {
// seach the db for a resource that matches
// purely for demonstration purposes
const order = {
order: {
id: '507f191e810c19729de860ea',
customer: 'John Doe',
},
};
if (req.params.id === '507f191e810c19729de860ea') res.xml(order);
else res.status(404).send('order not found');
};
This is my test:
describe('user endpoints', () => {
const consoleTransport = logger.transports.find(
(transport) => transport.level === 'info',
);
let app: Server;
before(() => {
app = createApp();
if (!consoleTransport) return;
consoleTransport.silent = true;
});
after(() => {
if (!consoleTransport) return;
consoleTransport.silent = false;
});
describe('GET /order/507f191e810c19729de860ea', () => {
it('returns 200 if the order exists and responds with the order', (done) => {
request(app)
.get('/order/507f191e810c19729de860ea')
.set('Accept', 'application/xml')
.expect('Content-Type', 'application/xml; charset=utf-8')
.expect((res: Request) => {
console.log('---- \n', res.body);
})
.expect(200, done);
});
});
The res.body in the last console log is an empty object. The console.log('oogabooga') is triggered after the the last console log. Is there a way I can fix these timings?
The log:
----
{}
//test fails
oogabooga