Skip to content

Commit

Permalink
feat: Improve isString diff
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed Sep 24, 2023
1 parent 7d92ce9 commit 5c73fbb
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 6 deletions.
44 changes: 40 additions & 4 deletions src/expectation/it.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,10 +197,46 @@ const isString = ({
return matching?.test(actual) ?? true;
},
{
toJSON: () =>
containing || matching
? `string(${printExpected(containing || matching)})`
: 'string',
toJSON: () => {
if (containing) {
return `string('${containing}')`;
}

if (matching) {
return `string(${matching})`;
}

return 'string';
},
getDiff: (actual) => {
if (typeof actual !== 'string') {
return {
expected: 'string',
actual: `${actual} (${typeof actual})`,
};
}

if (containing) {
if (actual.indexOf(containing) === -1) {
return {
expected: `string containing '${containing}'`,
actual,
};
}
}

if (matching) {
if (!matching.test(actual)) {
return {
expected: `string matching ${matching}`,
actual,
};
}
}

// Return the actual value twice to get a 0-diff.
return { expected: actual, actual };
},
}
);
};
Expand Down
43 changes: 41 additions & 2 deletions src/expectation/matcher.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { It } from './it';
import { expectAnsilessEqual } from '../../tests/ansiless';
import { It } from './it';

describe('It', () => {
describe('deepEquals', () => {
Expand Down Expand Up @@ -423,13 +423,52 @@ describe('It', () => {
expectAnsilessEqual(It.isString().toJSON(), 'string');
expectAnsilessEqual(
It.isString({ containing: 'foo' }).toJSON(),
'string("foo")'
"string('foo')"
);
expectAnsilessEqual(
It.isString({ matching: /bar/ }).toJSON(),
'string(/bar/)'
);
});

it("should print diff when there's a match", () => {
expect(It.isString().getDiff('foo')).toEqual({
actual: 'foo',
expected: 'foo',
});

expect(It.isString({ containing: 'foo' }).getDiff('foobar')).toEqual({
actual: 'foobar',
expected: 'foobar',
});

expect(It.isString({ matching: /foo/ }).getDiff('foobar')).toEqual({
actual: 'foobar',
expected: 'foobar',
});
});

it("should print diff when there's a mismatch", () => {
expect(It.isString().getDiff(42)).toEqual({
actual: '42 (number)',
expected: 'string',
});

expect(It.isString({ containing: 'foo' }).getDiff(42)).toEqual({
actual: '42 (number)',
expected: 'string',
});

expect(It.isString({ containing: 'foo' }).getDiff('bar')).toEqual({
actual: 'bar',
expected: "string containing 'foo'",
});

expect(It.isString({ matching: /foo/ }).getDiff('bar')).toEqual({
actual: 'bar',
expected: 'string matching /foo/',
});
});
});

describe('isArray', () => {
Expand Down

0 comments on commit 5c73fbb

Please sign in to comment.