Skip to content

Commit

Permalink
refactor: Improve isArray diff
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed Sep 24, 2023
1 parent df7f91a commit 89dc632
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
10 changes: 10 additions & 0 deletions src/matchers/is-array.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,16 @@ describe('isArray', () => {
actual: '42 (number)',
});

expect(isArray().getDiff({ foo: 'bar' })).toEqual({
expected: 'array',
actual: '{"foo": "bar"} (object)',
});

expect(isArray([1, 2]).getDiff(42)).toEqual({
expected: 'array containing [1, 2]',
actual: 42,
});

expect(isArray([1, 2]).getDiff([2])).toEqual({
expected: 'array containing [1, 2]',
actual: [2],
Expand Down
11 changes: 3 additions & 8 deletions src/matchers/is-array.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { printExpected } from 'jest-matcher-utils';
import stripAnsi from 'strip-ansi';
import { printArg } from '../print';
import { deepEquals } from './deep-equals';
import type { TypeMatcher } from './matcher';
import { isMatcher, matches } from './matcher';
Expand Down Expand Up @@ -49,13 +51,6 @@ export 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,
Expand All @@ -72,7 +67,7 @@ export const isArray = <T extends unknown[]>(containing?: T): TypeMatcher<T> =>
}

return {
actual,
actual: `${stripAnsi(printArg(actual, true))} (${typeof actual})`,
expected: 'array',
};
},
Expand Down
2 changes: 1 addition & 1 deletion src/print.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const printProperty = (property: Property) => {
return `.${property}`;
};

const printArg = (arg: unknown, received = false): string => {
export const printArg = (arg: unknown, received = false): string => {
// Call toJSON on matchers directly to avoid wrapping strings returned by them in quotes.
if (isMatcher(arg)) {
return arg.toJSON();
Expand Down

0 comments on commit 89dc632

Please sign in to comment.