Bringing it Together
Let’s combine the code we’ve written in the previous lessons of this chapter.
We'll cover the following...
Setting up files
Two things are still missing. The obvious one is the index file that glues everything together. We also need to respond in a RESTful way when answering our callers, that is , giving a status code and other details. Add this to our specifics
folder:
import {okResponse} from "../../../util/common/responses"; describe('responses test', () => { it('should return a 200 response for ok response', () => { const result = okResponse('OK') expect(result.statusCode).toBe(200); expect(result.body).toBe('OK'); }); });
The responsesTest.ts file
That should be easy enough to implement.
Press + to interact
import {Response} from "../../../../util/domain/types";export const okResponse = (message: string): Response => ({statusCode: 200,body: message,});
Note that we created a new type, which we add to our types:
Press + to interact
export type Response = {statusCode: number,body: string,}
We also want to be able to report a failure with a 400 message. So, we add a test and implementation.
import {badRequestResponse} from "../../../util/common/responses"; describe('responses test', () => { it('should return a 400 response for bad request response', () => { const result = badRequestResponse('Error') expect(result.statusCode).toBe(400); expect(result.body).toBe('Error'); }); });
The responsesTest.ts file
Press + to interact
export const badRequestResponse = (err: string): Response => ({statusCode: 400,body: err,});
Now we are ready to combine all of the parts. Let us write tests for the index.
Press + to interact
import {handler} from "../src";describe('create index test', () => {it('should return a 400 with message if start is later than end', async () => {const now = new Date();const oneHourInFuture = new Date(now.getTime() + 60 * 60 * 1000);const eventData = {hotelId: '1',userId: '11',start: oneHourInFuture,end: now,timestamp: now,}const event = {body: JSON.stringify(eventData),}const result = await handler(event);expect(result.statusCode).toBe(400);expect(result.body).toBe('Start date should be before end date');});it('should return 200 if everything is ok', async () => {const now = new Date();const oneHourInFuture = new Date(now.getTime() + 60 * 60 * 1000);const eventData = {hotelId: '1',userId: '11',start: now,end: oneHourInFuture,timestamp: now,}const event = {body: JSON.stringify(eventData),}const result = await handler(event);expect(result.statusCode).toBe(200);expect(result.body).toBe('Reservation created');});});
As we mentioned earlier, it might become difficult to test our index file when we add ...