// (C) 2007-2019 GoodData Corporation import { Application, Request, Response } from "express"; import { isEqual } from "lodash"; import * as HttpStatusCodes from "http-status-codes"; export interface IMockResponseConfig { params?: { [key: string]: any }; query?: { [key: string]: any }; headers?: { [key: string]: any }; body?: { [key: string]: any }; response: any; } function isRequestHeadersMatching(headers: any, config: IMockResponseConfig) { if (!config.headers) { return true; } if (!headers) { return false; } return Object.keys(config.headers).every(key => config.headers[key] === headers[key]); } export function isMockRequestMatching(req: Request, config: IMockResponseConfig) { const keysMatch = ["params", "query", "body"].every(key => isEqual(req[key] || {}, config[key] || {})); const headersMatch = isRequestHeadersMatching(req.headers, config); return keysMatch && headersMatch; } export function getMatchingResponse(req: Request, mocks: IMockResponseConfig[] = []) { return mocks.find(mock => isMockRequestMatching(req, mock)); } type HttpMethod = "get" | "post"; export function mock( app: Application, method: HttpMethod, uri: string, mockConfigs: IMockResponseConfig[], defaultMockConfig: IMockResponseConfig = null, ) { app[method](uri, (req: Request, res: Response) => { const mockedResponseConfig = getMatchingResponse(req, mockConfigs) || defaultMockConfig; if (mockedResponseConfig) { res.status(HttpStatusCodes.OK).json(mockedResponseConfig.response); return; } res.status(HttpStatusCodes.BAD_REQUEST).send("Can't find mock for this request"); }); }