From a5aaddd0a28108dd82d204914b1b5f00a6ac9cca Mon Sep 17 00:00:00 2001 From: Andrei Picus Date: Mon, 12 Jun 2023 20:54:54 +0200 Subject: [PATCH] feat: Improve `isArray` diff --- src/expectation/it.ts | 22 ++++++++++++++++++++++ src/expectation/matcher.spec.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/expectation/it.ts b/src/expectation/it.ts index 335c0ab..9efa31b 100644 --- a/src/expectation/it.ts +++ b/src/expectation/it.ts @@ -286,6 +286,28 @@ const isArray = (containing?: T): TypeMatcher => { toJSON: () => containing ? `array(${printExpected(containing)})` : 'array', + getDiff: (actual) => { + if (!Array.isArray(actual)) { + return { actual: `${actual} (${typeof actual})`, expected: 'array' }; + } + + if (containing) { + return { + actual, + expected: `array containing [${containing + .map((value) => { + if (isMatcher(value)) { + return value.toJSON(); + } + + return value; + }) + .join(', ')}]`, + }; + } + + return { actual, expected: 'array' }; + }, } ); diff --git a/src/expectation/matcher.spec.ts b/src/expectation/matcher.spec.ts index dbd0b41..a1b20b5 100644 --- a/src/expectation/matcher.spec.ts +++ b/src/expectation/matcher.spec.ts @@ -529,6 +529,32 @@ describe('It', () => { expectAnsilessEqual(It.isArray().toJSON(), 'array'); expectAnsilessEqual(It.isArray([1, 2, 3]).toJSON(), 'array([1, 2, 3])'); }); + + it('should print diff', () => { + expect(It.isArray().getDiff(42)).toEqual({ + expected: 'array', + actual: '42 (number)', + }); + + expect(It.isArray([1, 2]).getDiff([2])).toEqual({ + expected: 'array containing [1, 2]', + actual: [2], + }); + }); + + it('should print diff with stringified nested matchers', () => { + const matcher = It.matches(() => false, { + toJSON: () => 'something', + getDiff: () => { + throw new Error(); + }, + }); + + expect(It.isArray([matcher, matcher]).getDiff([2])).toEqual({ + expected: 'array containing [something, something]', + actual: [2], + }); + }); }); describe('matches', () => {