Sanitizing ArrayBuffer response [shorts]

Sanitizing ArrayBuffer response [shorts]

In this article, I will explain how to sanitize the ArrayBuffer response into the parsed JSON while debugging in Cypress.

This generally would happen when, you have custom commands for uploading file

Cypress Debugger
/**
 * This Command uploads a file to a given URL endpoint
 *
 * @param {String} url - full URL of the upload endpoint
 * @param {String} formData - formaData to be passed as body to endpoint
 */
Cypress.Commands.add("uploadFile", (url, formData) => {
	return cy.request({
		method: 'POST',
		url: url,
		body: formData,
		failOnStatusCode: false
	}).as('uploadFileRequest')

}

cypress commands.js

In order to debug the error happening while development, we need to render the response of '@uploadFile' in a readable format. There are 2 ways how we can achieve that.

1) Using Cypress.Blob:

function arrayBufferToJSON(aliasName) {
	console.log(`Converting ${aliasName} ArrayBuffer data to JSON data..`)
	return cy.get(`${aliasName}`)
		.then(response => {
		   //check ArrayBuffer.byteLength > 0
		   if (response.body.byteLength > 0) {
			// convert response.body ArrayBuffer to JSON object
			let responseBodyJSON = Cypress.Blob.arrayBufferToBinaryString(response.body);
			response.body = JSON.parse(responseBodyJSON);

		   } else{
			//set response.body to '' if arrayBuffer.byteLength is 0
			response.body = ''
		   }

		   return JSON.stringify(response);

		})
		.then(res => JSON.parse(res))
		.then(async (data) => {
			return data;
		})

}

cypress commands.js

2) Using vanilla.js:

function arrayBufferToJSON(aliasName) {
	console.log(`Converting ${aliasName} ArrayBuffer data to JSON data..`)
	return cy.get(`${aliasName}`).then(async (data) => {
		//check ArrayBuffer.byteLength > 0
		if (data.body.byteLength > 0) {
			//convert data ArrayBuffer to JSON object
			var jsonResponse = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(data.body)))
			data.body = jsonResponse
		} else {
			//set data.body to '' if arrayBuffer.byteLength is 0
			data.body = ''
		}

		return data;
	});
}

cypress commands.js

Once we have these methods we have to wrap our original command like below. In both the cases we need to pass on the cypress alias to these santizing functions and we retrieve the actual response and then convert them to Parsed JSON response before sending back to calling code.

Cypress.Commands.add("reuploadFile", (url, formData) => {
	cy.request({
		method: 'PUT',
		url: url,
		body: formData,
		failOnStatusCode: false
	}).as('reuploadFileRequest')

	return arrayBufferToJSON("@reuploadFileRequest");
})

After updating our code, it will work in the code as well as on the debugger

Fixed Cypress debugging

Cheers!!

Happy Monday!!