Skip to content

Commit

Permalink
feat: Improve isArray diff
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed Sep 24, 2023
1 parent 5c73fbb commit a5aaddd
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/expectation/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,28 @@ const isArray = <T extends unknown[]>(containing?: T): TypeMatcher<T> =>
{
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' };
},
}
);

Expand Down
26 changes: 26 additions & 0 deletions src/expectation/matcher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit a5aaddd

Please sign in to comment.