Skip to content

Commit 9239c5d

Browse files
committed
all body assertions check utf8
1 parent c92ade4 commit 9239c5d

File tree

1 file changed

+26
-18
lines changed

1 file changed

+26
-18
lines changed

src/audits/utils.ts

+26-18
Original file line numberDiff line numberDiff line change
@@ -113,12 +113,7 @@ export function ressert(res: Response) {
113113
bodyAsExecutionResult: {
114114
data: {
115115
async toBe(val: ExecutionResult['data']) {
116-
let body: ExecutionResult;
117-
try {
118-
body = await res.json();
119-
} catch (err) {
120-
throw new AuditError(res, 'Response body is not valid JSON');
121-
}
116+
const body = await assertBodyAsExecutionResult(res);
122117
if (body.data !== val) {
123118
throw new AuditError(
124119
res,
@@ -128,12 +123,7 @@ export function ressert(res: Response) {
128123
},
129124
},
130125
async toHaveProperty(key: keyof ExecutionResult) {
131-
let body: ExecutionResult;
132-
try {
133-
body = await res.json();
134-
} catch (err) {
135-
throw new AuditError(res, 'Response body is not valid JSON');
136-
}
126+
const body = await assertBodyAsExecutionResult(res);
137127
if (!(key in body)) {
138128
throw new AuditError(
139129
res,
@@ -142,12 +132,7 @@ export function ressert(res: Response) {
142132
}
143133
},
144134
async notToHaveProperty(key: keyof ExecutionResult) {
145-
let body: ExecutionResult;
146-
try {
147-
body = await res.json();
148-
} catch (err) {
149-
throw new AuditError(res, 'Response body is not valid JSON');
150-
}
135+
const body = await assertBodyAsExecutionResult(res);
151136
if (key in body) {
152137
throw new AuditError(
153138
res,
@@ -158,3 +143,26 @@ export function ressert(res: Response) {
158143
},
159144
};
160145
}
146+
147+
/** @private */
148+
async function assertBodyAsExecutionResult(
149+
res: Response,
150+
): Promise<ExecutionResult> {
151+
let decoded: string;
152+
try {
153+
const decoder = new TextDecoder('utf-8');
154+
const buff = await res.arrayBuffer();
155+
decoded = decoder.decode(buff);
156+
} catch (err) {
157+
throw new AuditError(res, 'Response body is not UTF-8 encoded');
158+
}
159+
160+
let body: ExecutionResult;
161+
try {
162+
body = JSON.parse(decoded);
163+
} catch (err) {
164+
throw new AuditError(res, 'Response body is not valid JSON');
165+
}
166+
167+
return body;
168+
}

0 commit comments

Comments
 (0)