-
-
Notifications
You must be signed in to change notification settings - Fork 225
/
Copy pathtoBeJsonMatching.js
25 lines (19 loc) · 1.05 KB
/
toBeJsonMatching.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { matchesObject, tryParseJSON } from '../utils';
export function toBeJsonMatching(actual, expected) {
const { printExpected, printReceived, matcherHint } = this.utils;
const parsed = tryParseJSON(actual);
const isValidJSON = typeof parsed !== 'undefined';
const passMessage =
`${matcherHint('.not.toBeJsonMatching')}\n\n` +
`Expected input to not be a JSON string containing:\n ${printExpected(expected)}\n` +
`${isValidJSON ? `Received:\n ${printReceived(parsed)}` : `Received invalid JSON:\n ${printReceived(actual)}`}`;
const failMessage =
`${matcherHint('.toBeJsonMatching')}\n\n` +
`Expected input to be a JSON string containing:\n ${printExpected(expected)}\n` +
`${isValidJSON ? `Received:\n ${printReceived(parsed)}` : `Received invalid JSON:\n ${printReceived(actual)}`}`;
const pass =
typeof actual === 'string' &&
typeof tryParseJSON(actual) !== 'undefined' &&
matchesObject(this.equals, tryParseJSON(actual), expected);
return { pass, message: () => (pass ? passMessage : failMessage) };
}