| 61 | // with green and red. (similar to how github does code diffing) |
| 62 | // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types |
| 63 | export function diff(a: any, b: any, options?: DiffOptions): string | null { |
| 64 | if (Object.is(a, b)) { |
| 65 | return getCommonMessage(NO_DIFF_MESSAGE, options); |
| 66 | } |
| 67 | |
| 68 | const aType = getType(a); |
| 69 | let expectedType = aType; |
| 70 | let omitDifference = false; |
| 71 | if (aType === 'object' && typeof a.asymmetricMatch === 'function') { |
| 72 | if (a.$$typeof !== Symbol.for('jest.asymmetricMatcher')) { |
| 73 | // Do not know expected type of user-defined asymmetric matcher. |
| 74 | return null; |
| 75 | } |
| 76 | if (typeof a.getExpectedType !== 'function') { |
| 77 | // For example, expect.anything() matches either null or undefined |
| 78 | return null; |
| 79 | } |
| 80 | expectedType = a.getExpectedType(); |
| 81 | // Primitive types boolean and number omit difference below. |
| 82 | // For example, omit difference for expect.stringMatching(regexp) |
| 83 | omitDifference = expectedType === 'string'; |
| 84 | } |
| 85 | |
| 86 | if (expectedType !== getType(b)) { |
| 87 | return ( |
| 88 | ' Comparing two different types of values.' + |
| 89 | ` Expected ${chalk.green(expectedType)} but ` + |
| 90 | `received ${chalk.red(getType(b))}.` |
| 91 | ); |
| 92 | } |
| 93 | |
| 94 | if (omitDifference) { |
| 95 | return null; |
| 96 | } |
| 97 | |
| 98 | switch (aType) { |
| 99 | case 'string': |
| 100 | return diffLinesUnified( |
| 101 | escapeControlCharacters(a).split('\n'), |
| 102 | escapeControlCharacters(b).split('\n'), |
| 103 | options, |
| 104 | ); |
| 105 | case 'boolean': |
| 106 | case 'number': |
| 107 | return comparePrimitive(a, b, options); |
| 108 | case 'map': |
| 109 | return compareObjects(sortMap(a), sortMap(b), options); |
| 110 | case 'set': |
| 111 | return compareObjects(sortSet(a), sortSet(b), options); |
| 112 | default: |
| 113 | return compareObjects(a, b, options); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | function comparePrimitive( |
| 118 | a: number | boolean, |