commercetools-8.x-1.2-alpha1/tests/src/Nightwatch/Lib/getResponseByDataTypeFromHashes.js
tests/src/Nightwatch/Lib/getResponseByDataTypeFromHashes.js
async function throwResponseError(browser, hash, response, type) {
const responseMetadata = await browser.thGetRequestMetadataByHash(hash);
const operation = JSON.parse(responseMetadata.request.body);
throw new Error(
`Response for a request with hash "${hash}" has ${type}: ${JSON.stringify(
response[type],
null,
2,
)}\nQuery: ${operation.query}\nVariables: ${JSON.stringify(
operation.variables,
null,
2,
)}`,
);
}
module.exports = async function getResponseByDataTypeFromHashes(
browser,
hashes,
dataType,
skipErrorCheck = false,
) {
const responseDataTypes = [];
let matchedResult = null;
for (let i = 0; i < hashes.length; i++) {
let hashResponse;
// We have to use await in the loop.
// eslint-disable-next-line no-await-in-loop
await browser.perform(async () => {
hashResponse = await browser.thGetRequestResponseByHash(hashes[i]);
});
const hashResult = JSON.parse(hashResponse);
if (!skipErrorCheck) {
if (hashResult.errors !== undefined) {
// eslint-disable-next-line no-await-in-loop
await throwResponseError(browser, hashes[i], hashResult, 'errors');
}
}
if (hashResult.data !== undefined) {
const responseDataType = Object.keys(hashResult.data)[0];
if (responseDataType === dataType) {
matchedResult = {
hash: hashes[i],
value: hashResult,
};
break;
}
responseDataTypes.push(responseDataType);
}
}
if (matchedResult === null) {
throw new Error(
`No response with the data type "${dataType}" found, received datatypes: ${responseDataTypes.join(
', ',
)}.`,
);
}
return matchedResult;
};
