How to use hasJsonContentType method in Cypress

Best JavaScript code snippet using cypress

validateBody.js

Source:validateBody.js Github

copy

Full Screen

1const mediaTyper = require('media-typer');2const contentTypeUtils = require('content-type');3const { isValidField } = require('./isValid');4const { TextDiff, JsonExample, JsonSchemaValidator } = require('../validators');5const isset = require('../utils/isset');6const parseJson = require('../utils/parseJson');7function isPlainText(mediaType) {8  return mediaType.type === 'text' && mediaType.subtype === 'plain';9}10function isJson(mediaType) {11  if (!mediaType) {12    return false;13  }14  return (15    (mediaType.type === 'application' && mediaType.subtype === 'json') ||16    mediaType.suffix === 'json'17  );18}19function isJsonSchema(mediaType) {20  if (!mediaType) {21    return false;22  }23  return (24    mediaType.type === 'application' &&25    mediaType.subtype === 'schema' &&26    mediaType.suffix === 'json'27  );28}29/**30 * Parses a given content-type header into media type.31 * @param {string} contentType32 * @returns {[Error, MediaType]}33 */34function parseContentType(contentType) {35  try {36    const { type } = contentTypeUtils.parse(`${contentType}`);37    return mediaTyper.parse(type);38  } catch (error) {39    return null;40  }41}42/**43 * Determines if a given 'Content-Type' header contains JSON.44 * @param {string} contentType45 * @returns {boolean}46 */47function isJsonContentType(contentType) {48  const mediaType = parseContentType(contentType);49  return mediaType ? isJson(mediaType) : false;50}51/**52 * Returns a tuple of error and body media type based53 * on the given body and normalized headers.54 * @param {string} body55 * @param {string} contentType56 * @param {'actual'|'expected'} httpMessageOrigin57 * @returns {[string, MediaType]}58 */59function getBodyType(body, contentType, httpMessageOrigin) {60  const hasJsonContentType = isJsonContentType(contentType);61  try {62    parseJson(body);63    const bodyMediaType = parseContentType(64      hasJsonContentType ? contentType : 'application/json'65    );66    return [null, bodyMediaType];67  } catch (parsingError) {68    const fallbackMediaType = mediaTyper.parse('text/plain');69    const error = hasJsonContentType70      ? `Can't validate: ${httpMessageOrigin} body 'Content-Type' header is '${contentType}' \71but body is not a parseable JSON:72${parsingError.message}`73      : null;74    return [error, fallbackMediaType];75  }76}77/**78 * Returns a tuple of error and schema media type79 * based on given body schema.80 * @param {string} bodySchema81 * @returns {[string, string]}82 */83function getBodySchemaType(bodySchema) {84  const jsonSchemaType = mediaTyper.parse('application/schema+json');85  if (typeof bodySchema !== 'string') {86    return [null, jsonSchemaType];87  }88  try {89    parseJson(bodySchema);90    return [null, jsonSchemaType];91  } catch (error) {92    // Gavel must throw when given malformed JSON Schema.93    // See https://github.com/apiaryio/gavel.js/issues/20394    throw new Error(`\95Failed to validate HTTP message "body": given JSON Schema is not a valid JSON.96${error.message}\97`);98  }99}100/**101 * Returns a body validator class based on the given102 * actual and expected body media types.103 * @param {MediaType} expectedType104 * @param {MediaType} actualType105 * @returns {Validator}106 */107function getBodyValidator(expectedType, actualType) {108  const both = (predicate) => (expected, actual) => {109    return [expected, actual].every(predicate);110  };111  const validators = [112    [TextDiff, both(isPlainText), 'text'],113    // List JsonSchema first, because weak predicate of JsonExample114    // would resolve on "application/schema+json" media type too.115    [116      JsonSchemaValidator,117      (expected, actual) => {118        return isJson(actual) && isJsonSchema(expected);119      },120      'json'121    ],122    [JsonExample, both(isJson), 'json']123  ];124  const validator = validators.find(([_name, predicate]) => {125    return predicate(expectedType, actualType);126  });127  if (!validator) {128    const error = `Can't validate actual media type '${mediaTyper.format(129      actualType130    )}' against the expected media type '${mediaTyper.format(expectedType)}'.`;131    return [error, null, null];132  }133  return [null, validator[0], validator[2]];134}135/**136 * Validates given bodies of transaction elements.137 * @param {Object<string, any>} expected138 * @param {Object<string, any>} actual139 */140function validateBody(expected, actual) {141  const values = {142    actual: actual.body143  };144  // Prevent assigning { expected: undefined }.145  // Also ignore "bodySchema" as the expected value.146  if (isset(expected.body)) {147    values.expected = expected.body;148  }149  const errors = [];150  const actualBodyType = typeof actual.body;151  const hasEmptyActualBody = actual.body === '';152  // Throw when user input for actual body is not a string.153  if (actualBodyType !== 'string') {154    throw new Error(155      `Expected HTTP body to be a string, but got: ${actualBodyType}`156    );157  }158  const [actualTypeError, actualType] = getBodyType(159    actual.body,160    actual.headers && actual.headers['content-type'],161    'actual'162  );163  const [expectedTypeError, expectedType] = expected.bodySchema164    ? getBodySchemaType(expected.bodySchema)165    : getBodyType(166        expected.body,167        expected.headers && expected.headers['content-type'],168        'expected'169      );170  if (actualTypeError) {171    errors.push({172      message: actualTypeError173    });174  }175  if (expectedTypeError) {176    errors.push({177      message: expectedTypeError178    });179  }180  const hasErrors = errors.length > 0;181  // Skipping body validation in case errors during182  // actual/expected body type definition.183  const [validatorError, ValidatorClass, kind] = hasErrors184    ? [null, null, null]185    : getBodyValidator(expectedType, actualType);186  if (validatorError) {187    // In case determined media types mismtach, check if the actual is not missing.188    // Keep in mind the following scenarios:189    // 1. Expected '', and got '' (TextDiff/TextDiff, valid)190    // 2. Expected {...}, but got '' (Json/TextDiff, invalid, produces "missing actual body" error)191    // 3. Expected {...}, but got "foo" (Json/TextDiff, invalid, produces types mismatch error).192    if (expected.body !== '' && hasEmptyActualBody) {193      errors.push({194        message: `Expected "body" of "${mediaTyper.format(195          expectedType196        )}" media type, but actual "body" is missing.`197      });198    } else {199      errors.push({200        message: validatorError201      });202    }203  }204  const usesJsonSchema =205    ValidatorClass && ValidatorClass.name === 'JsonSchemaValidator';206  const validator =207    ValidatorClass &&208    new ValidatorClass(usesJsonSchema ? expected.bodySchema : expected.body);209  const validationErrors = validator ? validator.validate(actual.body) : [];210  errors.push(...validationErrors);211  return {212    valid: isValidField({ errors }),213    kind,214    values,215    errors216  };217}218module.exports = {219  validateBody,220  isJson,221  isJsonSchema,222  isJsonContentType,223  parseContentType,224  getBodyType,225  getBodySchemaType,226  getBodyValidator...

Full Screen

Full Screen

transformers.js

Source:transformers.js Github

copy

Full Screen

1const logTags = require('../logTags');2const pick = require('lodash/pick');3const pickBy = require('lodash/pickBy');4const mapValues = require('lodash/mapValues');5const isObject = require('lodash/isObject');6const url = require('url');7const isHealth = require('./isHealth');8const { extractHeaders, truncateText } = require('../utils');9const mapValuesDeep = (v, callback) => (isObject(v) ? mapValues(v, v => mapValuesDeep(v, callback)) : callback(v));10const truncateTextWithLength = length => v =>11  (typeof v === 'string' && truncateText(v, length, '[Trimmed by riviere]')) || v;12const mapError = ({ ctx, err }) => {13  err.action = `${ctx.logCtx.method}${ctx.request.path}`;14  err.params = {15    query: ctx.request.query,16    body: ctx.request.body,17    log_tag: logTags.CATEGORY.UNEXPECTED_ERROR.TAG18  };19  err.context = Object.assign(err.context || {}, ctx.logCtx);20  return err;21};22const mapInReq = ({ ctx, health, bodyKeys, bodyKeysRegex, headersRegex, maxBodyValueChars }) => {23  if (isHealth(ctx, health)) {24    return Object.assign({}, ctx.logCtx, {25      log_tag: logTags.CATEGORY.INBOUND_REQUEST_HEALTH.TAG26    });27  }28  const meta = extractRequestMeta(ctx, bodyKeys, bodyKeysRegex, maxBodyValueChars, headersRegex);29  let userAgent = getUserAgent(ctx.headers);30  return Object.assign({}, ctx.logCtx, meta, {31    log_tag: logTags.CATEGORY.INBOUND_REQUEST.TAG,32    userAgent33  });34};35const mapInRes = (res, req, startedAt, reqId) => {36  const duration = new Date().getTime() - startedAt;37  const status = res.statusCode;38  let contentLength = getContentLength(res.headers);39  let userAgent = getUserAgent(res.headers);40  return {41    ...pick(req, ['method', 'protocol', 'host', 'path', 'query', 'href']),42    status,43    duration,44    requestId: reqId,45    contentLength,46    userAgent,47    log_tag: logTags.CATEGORY.INBOUND_RESPONSE.TAG48  };49};50const mapOutReq = (requestOptions, reqId, opts = {}) => {51  const method = requestOptions.method;52  const port = requestOptions.port;53  const requestId = reqId;54  const headersRegex = opts.headersRegex;55  const { protocol, host, path, query, href } = getUrlParameters(requestOptions);56  const { maxQueryChars, maxPathChars, maxHrefChars } = opts;57  const slicedQuery = truncateText(query, maxQueryChars);58  const slicedPath = truncateText(path, maxPathChars);59  const slicedHref = truncateText(href, maxHrefChars);60  const metaHeaders = extractHeaders(headersRegex, requestOptions.headers);61  let metaBody = {};62  const hasJsonContentType =63    requestOptions.headers &&64    ((requestOptions.headers['Content-type'] && requestOptions.headers['Content-type'].includes('application/json')) ||65      (requestOptions.headers['content-type'] && requestOptions.headers['content-type'].includes('application/json')) ||66      (requestOptions.headers['Content-Type'] && requestOptions.headers['Content-Type'].includes('application/json')));67  const isProperMethod = method === 'POST' || method === 'PUT' || method === 'PATCH';68  const isValidToExtractBody =69    isProperMethod && requestOptions.body && hasJsonContentType && (opts.bodyKeys || opts.bodyKeysRegex);70  if (isValidToExtractBody) {71    try {72      const jsonObject = JSON.parse(requestOptions.body);73      let picked = opts.maxBodyValueChars74        ? mapValuesDeep(jsonObject, truncateTextWithLength(opts.maxBodyValueChars))75        : jsonObject;76      if (opts.bodyKeysRegex) {77        const REGEX = opts.bodyKeysRegex;78        picked = pickBy(picked, (_, key) => REGEX.test(key));79      } else {80        picked = pick(picked, opts.bodyKeys);81      }82      if (Object.keys(picked).length) {83        metaBody = { body: picked };84      }85    } catch (e) {}86  }87  let contentLength = getContentLength(requestOptions.headers);88  return {89    metaHeaders,90    method,91    protocol,92    host,93    port,94    metaBody,95    path: slicedPath,96    query: slicedQuery,97    href: slicedHref,98    requestId,99    contentLength,100    log_tag: logTags.CATEGORY.OUTBOUND_REQUEST.TAG101  };102};103const mapOutRes = ({ ctx, health, bodyKeys, bodyKeysRegex, headersRegex, maxBodyValueChars }) => {104  const status = ctx.status;105  const duration = new Date().getTime() - ctx.state.riviereStartedAt;106  const headers = extractHeaders(headersRegex, ctx.response.headers);107  if (isHealth(ctx, health)) {108    return Object.assign({}, ctx.logCtx, {109      log_tag: logTags.CATEGORY.OUTBOUND_RESPONSE_HEALTH.TAG,110      status,111      duration112    });113  }114  const meta = extractRequestMeta(ctx, bodyKeys, bodyKeysRegex, maxBodyValueChars, headersRegex, 'request');115  let contentLength = ctx.state.calculatedContentLength || 0;116  let userAgent = getUserAgent(ctx.headers);117  return Object.assign({ status, duration, headers }, ctx.logCtx, meta, {118    log_tag: logTags.CATEGORY.OUTBOUND_RESPONSE.TAG,119    contentLength,120    userAgent121  });122};123function extractRequestMeta(ctx, bodyKeys, bodyKeysRegex, maxBodyValueChars, headersRegex, prefix = '') {124  const method = ctx.request.method;125  // pick headers126  const metaHeaders = extractHeaders(headersRegex, ctx.request.headers, prefix);127  // pick body128  let metaBody;129  const isProperMethod = method === 'POST' || method === 'PUT' || method === 'PATCH';130  if (isProperMethod && (bodyKeys || bodyKeysRegex) && typeof ctx.request.body === 'object') {131    let picked = maxBodyValueChars132      ? mapValuesDeep(ctx.request.body, truncateTextWithLength(maxBodyValueChars))133      : ctx.request.body;134    if (bodyKeysRegex) {135      const REGEX = bodyKeysRegex;136      picked = pickBy(picked, (_, key) => REGEX.test(key));137    } else {138      picked = pick(picked, bodyKeys);139    }140    if (Object.keys(picked).length) {141      if (prefix) {142        metaBody = { [prefix]: { body: picked } };143      } else {144        metaBody = { body: picked };145      }146    }147  }148  const meta = {};149  if (metaHeaders && Object.keys(metaHeaders).length) {150    meta.metaHeaders = metaHeaders;151  }152  if (metaBody) {153    meta.metaBody = metaBody;154  }155  return meta;156}157const getContentLength = headers => {158  if (!headers) return 0;159  return headers['content-length'] || headers['Content-length'] || headers['Content-Length'] || 0;160};161const getUserAgent = headers => {162  if (!headers) return '';163  return headers['user-agent'] || headers['User-agent'] || headers['User-Agent'] || '';164};165const getUrlParameters = requestOptions => {166  const usedOptions = requestOptions.uri || requestOptions;167  let protocol = usedOptions.protocol;168  protocol = protocol && protocol.substring(0, protocol.length - 1);169  const host = usedOptions.hostname || usedOptions.host;170  const path = usedOptions.path || usedOptions.pathname;171  const query = usedOptions.query;172  const href = url.format(usedOptions);173  return { protocol, host, path, query, href };174};175module.exports = {176  mapError,177  mapInReq,178  mapInRes,179  mapOutReq,180  mapOutRes...

Full Screen

Full Screen

broker.js

Source:broker.js Github

copy

Full Screen

1import Cookie from "../cookie";2import { dateToApi, isDate } from "lib/support/dates";3import dayjs from "dayjs";4export function getCsrfToken() {5	return decodeURIComponent(Cookie.get("XSRF-TOKEN"));6}7/**8 * @param {Object} headers9 * @returns {{Accept: string, 'X-XSRF-TOKEN': string}}10 */11function baseHeaders(headers = {}) {12	return {13		"X-XSRF-TOKEN": getCsrfToken(),14		Accept: "application/json",15		"Content-Type": "application/json",16		...headers,17	};18}19/**20 * @param {String} url21 * @param {"GET"|"POST"|"PUT"|"PATCH"|"DELETE"} method22 * @param {Object} params - Data sent as url parameters23 * @param {Object} config - Data sent in the body24 * @returns {Promise<unknown>}25 */26function apiRequest(url, method = "GET", params = null, config = {}) {27	const prefix = url.startsWith("/") ? "/api" : "/api/";28	const requestConfig = {};29	const requestUrl = new URL(prefix + url, document.location.href);30	const headers = baseHeaders(config?.headers || {});31	const hasParams = Boolean(params);32	const hasJsonContentType = headers["Content-Type"] === "application/json";33	requestConfig.method = method;34	requestConfig.headers = headers;35	// Parameters as url on GET method36	if (hasParams && typeof params === "object" && method === "GET") {37		Object.entries(params).forEach(([key, value]) => {38			requestUrl.searchParams.set(key, value.toString());39		});40	} else if (hasParams) {41		requestConfig.body = hasJsonContentType ? JSON.stringify(params) : params;42	}43	// The browser handle the correct content type44	// for us when handling complicated multi-part form data.45	if (hasParams && params instanceof FormData) {46		delete requestConfig.headers["Content-Type"];47	}48	return new Promise((resolve, reject) => {49		fetch(requestUrl.href, requestConfig)50			.then((res) => handleRequestResponse(res, resolve, reject))51			.catch((err) => handeRequestError(err, resolve, reject));52	});53}54/**55 * @param {Response} response56 */57function isResponseJsonParsable(response) {58	if (response.status === 204) {59		return false;60	}61	return response.headers.get("Content-Type") === "application/json";62}63/**64 * @param {Response} response65 * @param {Function} resolve66 * @param {Function} reject67 */68function handleRequestResponse(response, resolve, reject) {69	if (!response.ok) {70		response71			.json()72			.then((data) => reject(data, response))73			.catch(reject);74		return;75	}76	// Handle json compatible responses77	if (isResponseJsonParsable(response)) {78		response79			.json()80			.then((data) => resolve(data, response))81			.catch(reject);82		return;83	}84	resolve(null, response);85}86/**87 * @param {Object} error88 * @param {Function} resolve89 * @param {Function} reject90 */91function handeRequestError(error, resolve, reject) {92	console.error(error);93	reject(error);94}95function requestCsrfToken() {96	console.info("[Auth] Requesting token");97	return new Promise((resolve, reject) => {98		fetch("/sanctum/csrf-cookie")99			.then((res) => handleRequestResponse(res, resolve, reject))100			.catch((err) => handeRequestError(err, resolve, reject));101	});102}103/**104 * Convert any empty value to an empty string.105 *106 * @param {Object} data107 * @returns {Object}108 */109export function formatEmptyValue(data) {110	return Object.fromEntries(Object.entries(data).map(([k, v]) => [k, v || ""]));111}112/**113 * Format any date object of the given object.114 *115 * @param {Object} data116 * @returns {Object}117 */118export function formatDatesValues(data) {119	return Object.fromEntries(120		Object.entries(data).map(([k, v]) => [k, isDate(v) || dayjs.isDayjs(v) ? dateToApi(v) : v])121	);122}123export function formatObjectValues(data) {124	function objectToArrayFields(obj, prefix) {125		const fields = {};126		Object.entries(obj).forEach(([k, v]) => {127			const key = `${prefix}[${k}]`;128			const value = v || "";129			if (value instanceof File) {130				fields[key] = value;131			} else if (dayjs.isDayjs(value)) {132				fields[key] = dateToApi(value.toDate());133			} else if (value instanceof Date) {134				fields[key] = dateToApi(value);135			} else if (typeof value === "object") {136				Object.assign(fields, objectToArrayFields(value, key));137			} else {138				fields[key] = value;139			}140		});141		return fields;142	}143	const fieldsToAppend = {};144	const fieldToFilters = [];145	Object.entries(data).forEach(([k, v]) => {146		if (typeof v !== "object" || v instanceof File) {147			return v || "";148		}149		fieldToFilters.push(k);150		Object.assign(fieldsToAppend, objectToArrayFields(v, k));151	});152	const filteredFields = Object.fromEntries(Object.entries(data).filter(([k]) => !fieldToFilters.includes(k)));153	return Object.assign({}, filteredFields, fieldsToAppend);154}155/**156 * Format singles files value by only keeping the origin File157 * to upload, and remove key/value pair when the field has not158 * been changed, and should not be processed by the backend.159 *160 * @param {Object} data161 * @param {String[]} fields162 * @returns {Object}163 */164export function formatAndFilterSingleFilesValues(data, fields) {165	const filteredData = Object.entries(data).filter(([name, value]) => {166		if (!fields.includes(name)) {167			return true;168		}169		if (!Array.isArray(value)) {170			return false;171		}172		// Remove the fields if not changed (not a new File object).173		return value[0]?.originFileObj;174	});175	//noinspection JSCheckFunctionSignatures176	return Object.fromEntries(177		filteredData.map(([name, value]) => {178			if (!fields.includes(name)) {179				return [name, value];180			}181			// The file need to be cleared182			if (!Array.isArray(value) || value.length === 0) {183				return [name, ""];184			}185			// New file has to be uploaded186			return [name, value[0].originFileObj];187		})188	);189}190const Api = {191	get: (url, data = null, config = {}) => apiRequest(url, "GET", data, config),192	post: (url, data = null, config = {}) => apiRequest(url, "POST", data, config),193	postMultipart: (url, data = null, config = {}) => {194		const mergedConfigs = { ...config, headers: { "Content-Type": "multipart/form-data", ...config.headers } };195		return apiRequest(url, "POST", data, mergedConfigs);196	},197	put: (url, data = null, config = {}) => apiRequest(url, "PUT", data, config),198	patch: (url, data = null, config = {}) => apiRequest(url, "PATCH", data, config),199	delete: (url, data = null, config = {}) => apiRequest(url, "DELETE", data, config),200	requestToken: requestCsrfToken,201	request: apiRequest,202};...

Full Screen

Full Screen

server.test.js

Source:server.test.js Github

copy

Full Screen

...29    const res = await mockDbMethod(brokenTodo);30    expect(res.statusCode).toBe(400);31  }32}33function hasJsonContentType(response) {34  expect(response.headers["content-type"]).toEqual(35    expect.stringContaining("json")36  );37}38describe("server", () => {39  beforeEach(() => jest.clearAllMocks());40  it("exists", () => {41    expect(typeof makeApp).toBe("function");42    expect(typeof app).toBe("function");43  });44  describe("GET /todos - list todos", () => {45    it("returns status 200", async () => {46      const res = await supertest(app).get("/todos");47      expect(res.statusCode).toBe(200);48    });49    it("returns content-type json", async () => {50      listTodos.mockResolvedValue([]);51      const res = await supertest(app).get("/todos");52      hasJsonContentType(res);53    });54    it("returns an array of todos", async () => {55      listTodos.mockResolvedValue([]);56      const res = await supertest(app).get("/todos");57      expect(Array.isArray(res.body)).toBe(true);58      expect(listTodos).toHaveBeenCalledTimes(1);59    });60  });61  describe("POST /todos - add todo", () => {62    let todo = { task: "buy milk" };63    async function doAddTodo(returnId = 1, newTodo = todo) {64      addTodo.mockResolvedValue({ id: returnId });65      return await supertest(app)66        .post("/todos")67        .set("Accept", "application/json")68        .send(newTodo);69    }70    it("returns content-type json", async () =>71      hasJsonContentType(await doAddTodo()));72    it("return 201 status code", async () => {73      const res = await doAddTodo();74      expect(res.statusCode).toBe(201);75    });76    77    it("return the id of the newly added todo", async () => {78      const randomId = Math.floor(Math.random() * 100) + 1;79      const res = await doAddTodo(randomId);80      expect(res.body).toEqual({ id: randomId });81      expect(addTodo).toHaveBeenCalledTimes(1);82      expect(addTodo.mock.calls[0][0]).toEqual(todo);83    });84    it('returns 400 if todo is not an object with a single key "task" or has a task with an empty string', async () => {85      let todoMissingKey = {};86      let res;87      res = await doAddTodo(1, todoMissingKey);88      expect(res.statusCode).toBe(400);89      let todoWithExtraKeys = { task: "buy milk", done: false };90      res = await doAddTodo(1, todoWithExtraKeys);91      expect(res.statusCode).toBe(400);92      let todoWithEmptyTask = { task: "" };93      res = await doAddTodo(1, todoWithEmptyTask);94      expect(res.statusCode).toBe(400);95      let todoWithNonStringTask = { task: {} };96      res = await doAddTodo(1, todoWithNonStringTask);97      expect(res.statusCode).toBe(400);98    });99  });100  describe("PUT /todos - edit todo", () => {101    let todo = { id: 1, task: "buy milk", done: false };102    async function doEditTodo(updatedTodo) {103      editTodo.mockResolvedValue({ status: "ok" });104      return await supertest(app)105        .put("/todos")106        .set("Accept", "application/json")107        .send(updatedTodo);108    }109    it("returns content-type json", async () =>110      hasJsonContentType(await doEditTodo()));111    it("returns status 200", async () => {112      const res = await doEditTodo(todo);113      expect(res.statusCode).toBe(200);114    });115    it('returns {status: "ok"} on success', async () => {116      const updatedTodo = { ...todo, done: true };117      const res = await doEditTodo(updatedTodo);118      expect(res.body).toEqual({ status: "ok" });119      expect(editTodo).toHaveBeenCalledTimes(1);120      expect(editTodo.mock.calls[0][0]).toEqual(updatedTodo);121    });122    it("returns status 400 if object shape is not: {id: int, task: str, done: bool}", async () => {123      await testBrokenTodos(doEditTodo);124    });125  });126  describe("DELETE /todos - delete todo", () => {127    let todo = { id: 1, task: "buy milk", done: true };128    async function doDeleteTodo(todoToDelete) {129      deleteTodo.mockResolvedValue({ status: "ok" });130      return await supertest(app)131        .delete("/todos")132        .set("Accept", "application/json")133        .send(todoToDelete);134    }135    it("returns content-type json", async () =>136      hasJsonContentType(await doDeleteTodo(todo)));137    it("returns status 200", async () => {138      const res = await doDeleteTodo(todo);139      expect(res.statusCode).toBe(200);140    });141    it('returns {status: "ok"} on success', async () => {142      const todoToDelete = { ...todo, done: true };143      const res = await doDeleteTodo(todoToDelete);144      expect(res.body).toEqual({ status: "ok" });145      expect(deleteTodo).toHaveBeenCalledTimes(1);146      expect(deleteTodo.mock.calls[0][0]).toEqual(todoToDelete);147    });148    it("returns status 400 if object shape is not: {id: int, task: str, done: bool}", async () => {149      await testBrokenTodos(doDeleteTodo);150    });...

Full Screen

Full Screen

router.js

Source:router.js Github

copy

Full Screen

1const HttpError = require('./HttpError');2function transformBody(body, type) {3  if (type === 'json') {4    return JSON.stringify(body);5  }6  return body;7}8function transformContentType(type) {9  if (type === 'json') {10    return `application/json`;11  }12  if (type === 'xml') {13    return `application/xml`;14  }15  return '';16}17function router(app) {18  async function onRequest(event, context, callback) {19    const {20      path,21      httpMethod: method,22      requestContext: {23        identity: {24          sourceIp,25          userAgent,26        },27      },28    } = event;29    const match = app.match(method, path);30    const requestStart = Date.now();31    function log(statusCode) {32      console.log(`method=${method} path=${path} status=${statusCode} duration=${Date.now() - requestStart}ms ip=${sourceIp} agent=${userAgent}`);33    }34    const success = (body = {}, statusCode = 200, type = 'json') => {35      log(statusCode);36      return ({37        statusCode: statusCode || 200,38        body: transformBody(body, type),39        headers: {40          'Access-Control-Allow-Origin': '*',41          'Access-Control-Allow-Credentials': true,42          'Content-Type': transformContentType(type),43        },44      });45    };46    const failed = (error = new HttpError('Server encountered an error.'), statusCode = 500) => {47      log(statusCode);48      return ({49        statusCode: statusCode || 500,50        body: JSON.stringify({ error: { message: `${error._httpSafe ? error.message : 'Server encountered an error.'}` } }),51        headers: {52          'Access-Control-Allow-Origin': '*',53          'Access-Control-Allow-Credentials': true,54        },55      });56    };57    if (! match) {58      const error = new Error('This resource does not exist.');59      error._httpSafe = true;60      return callback(null, failed(error, 404));61    }62    const [hits, routeHandler] = match;63    const { body = null, headers = {} } = event;64    let json = null;65    const lowercaseHeaders = Object.keys(headers)66      .reduce((acc, key) => ({67        ...acc,68        [key.toLowerCase()]: headers[key].toLowerCase(),69      }), {});70    const hasJsonContentType = lowercaseHeaders['content-type'] === 'application/json';71    if (hasJsonContentType && body && ['post', 'put'].includes(method.toLowerCase())) {72      try {73        json = JSON.parse(body);74      } catch(error) {75        return callback(null, failed('Malformed json body.', 400));76      }77    }78    try {79      const [path, ...params] = hits;80      const response = await routeHandler({81        event, context, callback,82        success, failed,83        path, params, json,84      });85      if (! response) {86        return callback(null, failed());87      }88      return callback(null, response);89    } catch (error) {90      console.error(error);91      return callback(null, failed(error));92    }93  }94  return onRequest;95}...

Full Screen

Full Screen

json.js

Source:json.js Github

copy

Full Screen

...21    }22    if (!hasGzipContentEncoding(req)) {23      return next();24    }25    if (!hasJsonContentType(req)) {26      return next();27    }28    req._body = true;29    var data = [];30    req.on("data", function(chunk) {31      data.push(new Buffer(chunk));32    });33    34    req.on("end", function() {35      buffer = Buffer.concat(data);36      zlib.gunzip(buffer, function(err, result) {37        if (err) {38          err.body = result;39          err.status = 400;...

Full Screen

Full Screen

fetchAsync.js

Source:fetchAsync.js Github

copy

Full Screen

...7  const protohost = protocol + '//' + host;8  const locRegex = new RegExp(protohost, 'i');9  return locRegex.test(url) ? url : protohost + url;10}11function hasJsonContentType(response) {12  const contentType = response.headers.get('content-type');13  return (14    contentType &&15    (contentType.includes('application/json') ||16      contentType.includes('text/plain'))17  );18}19export async function fetchAsync(20  url,21  option = { method: 'GET', body: undefined }22) {23  const { method, body } = option;24  try {25    const response = await fetch(fixURL(url), {26      method: method,27      headers: {28        'Content-Type': 'application/json',29      },30      body: JSON.stringify(body),31    });32    const jsonObj = hasJsonContentType(response) ? await response.json() : null;33    // console.log('jsonobj: ', jsonObj);34    return jsonObj;35  } catch (err) {36    console.error('fetchAsync: ', err.message);37    return null;38  }39}...

Full Screen

Full Screen

jsonrequest.js

Source:jsonrequest.js Github

copy

Full Screen

1'use strict';2module.exports = {3  processRequest: function(req) {4    var5      contentType = req.header('Content-Type'),6      hasJsonContentType = contentType &&7                           contentType.indexOf('application/json') !== -1;8    if (contentType != null && !hasJsonContentType) {9      return;10    }11    if (req.body) {12      if (!contentType) {13        req.header('Content-Type', 'application/json');14      }15      req.body = JSON.stringify(req.body);16    }17  }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.hasJsonContentType()2cy.hasJsonContentType()3cy.hasJsonContentType()4cy.hasJsonContentType()5Cypress.Commands.add('hasJsonContentType', () => {6  cy.get('@response').its('headers').its('content-type').should('include', 'application/json')7})8describe('Test', () => {9  it('should test', () => {10    cy.request('/api/users').as('response')11    cy.hasJsonContentType()12  })13})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('hasJsonContentType', () => {2  it('should have json content type', () => {3      .its('headers')4      .its('content-type')5      .should('include', 'application/json')6  })7})8Cypress.Commands.add('hasJsonContentType', () => {9    .its('headers')10    .its('content-type')11    .should('include', 'application/json')12})13import './commands'14describe('hasJsonContentType', () => {15  it('should have json content type', () => {16    cy.hasJsonContentType()17  })18})19Cypress.Commands.add('hasJsonContentType', () => {20    .its('headers')21    .its('content-type')22    .should('include', 'application/json')23})24import './commands'25describe('hasJsonContentType', () => {26  it('should have json content type', () => {27    cy.hasJsonContentType()28  })29})30Cypress.Commands.add('hasJsonContentType', () => {31    .its('headers')32    .its('content-type')33    .should('include', 'application/json')34})35import './commands'36describe('hasJsonContentType', () => {37  it('should have json content type', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { hasJsonContentType } from 'cypress/types/jquery';2describe('Test', () => {3    it('Test', () => {4        cy.request({5        }).then((response) => {6            expect(response.status).to.eq(405);7            expect(response).to.have.property('headers');8            expect(response.headers).to.have.property('content-type');9            hasJsonContentType(response.headers['content-type']);10        });11    });12});13CypressError: Timed out retrying: expected 'text/html; charset=UTF-8' to have a JSON content type14import { hasJsonContentType } from 'cypress/types/jquery';15describe('Test', () => {16    it('Test', () => {17        cy.request({18        }).then((response) => {19            expect(response.status).to.eq(405);20            expect(response).to.have.property('headers');21            expect(response.headers).to.have.property('content-type');22            hasJsonContentType(response.headers['content-type']);23        });24    });25});26Expected response to have JSON content type but it was "text/html; charset=UTF-8"27Expected response to NOT have JSON content type but it was "text/html; charset=UTF-8"28import { hasJsonContentType } from 'cypress/types/jquery';29describe('Test', () => {30    it('Test', () => {31        cy.request({32        }).then((response) => {33            expect(response.status).to

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should have json content type', () => {2    expect(response).to.have.jsonContentType3  })4})5Cypress.Commands.add('hasJsonContentType', (response) => {6  expect(response.headers['content-type']).to.include('application/json')7})8import './commands'9{10}11  1 passing (1s)

Full Screen

Using AI Code Generation

copy

Full Screen

1cy.hasJsonContentType();2cy.hasJsonContentType();3Cypress.Commands.add('hasJsonContentType', function() {4        .should((response) => {5            expect(response.headers['content-type']).to.include('application/json')6        })7});8describe('Test', () => {9    it('Test', () => {10        cy.hasJsonContentType();11        cy.hasJsonContentType();12    });13});14describe('Test', () => {15    beforeEach(() => {16        cy.hasJsonContentType();17    });18    it('Test', () => {19        cy.hasJsonContentType();20    });21    it('Test', () => {22        cy.hasJsonContentType();23    });24});25describe('Test', () => {26    before(() => {27        cy.hasJsonContentType();28    });29    it('Test', () => {30        cy.hasJsonContentType();31    });32    it('Test', () => {33        cy.hasJsonContentType();34    });35});36describe('Test', () => {37    it('Test', () => {38        cy.hasJsonContentType();39    });40});41describe('Test', () => {42    it('Test', () => {43        cy.hasJsonContentType();44    });45    it('Test', () => {46        cy.hasJsonContentType();47    });48});49describe('Test', () => {50    it('Test', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("Test", () => {2  it("should be true", () => {3    cy.request({4      headers: {5        "Content-Type": "application/json; charset=utf-8"6      },7      body: {8      }9    }).then(res => {10      expect(res.hasJsonContentType).to.be.true;11    });12  });13});14describe("Test", () => {15  it("should be true", () => {16    cy.request({17      headers: {18        "Content-Type": "application/json; charset=utf-8"19      },20      body: {21      }22    }).then(res => {23      expect(res.body).to.have.property("some");24    });25  });26});27describe("Test", () => {28  it("should be true", () => {29    cy.request({30      headers: {31        "Content-Type": "application/json; charset=utf-8"32      },33      body: {34      }35    }).then(res => {36      expect(res.status).to.equal(200);37    });38  });39});40describe("Test", () => {41  it("should be true", () => {42    cy.request({43      headers: {44        "Content-Type": "application/json; charset=utf-8"45      },46      body: {47      }48    }).then(res => {49      expect(res.status).to.equal(200);50    });51  });52});

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test to check the content type of response', () => {2    it('should check the content type of response', () => {3            .its('headers')4            .its('content-type')5            .should('include', 'application/json')6    })7})8Cypress.Commands.add('hasJsonContentType', () => {9        .its('headers')10        .its('content-type')11        .should('include', 'application/json')12})13describe('Test to check the content type of response', () => {14    it('should check the content type of response', () => {15        cy.hasJsonContentType()16    })17})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful