Skip to content

Commit

Permalink
feat: Improve error message for UnexpectedCalls
Browse files Browse the repository at this point in the history
  • Loading branch information
NiGhTTraX committed May 5, 2020
1 parent cc91ccc commit ff8636c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
25 changes: 24 additions & 1 deletion src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,32 @@ export class UnmetExpectations extends Error {
}
}

/**
* Merge property accesses and method calls for the same property
* into a single call.
*
* @example
* mergeCalls({ foo: [{ arguments: undefined }, { arguments: [1, 2, 3] }] }
* // returns { foo: [{ arguments: [1, 2, 3] } }
*/
const mergeCalls = (callMap: CallMap): CallMap => {
return new Map(
Array.from(callMap.entries()).map(([property, calls]) => {
const hasMethodCalls = calls.some((call) => call.arguments);
const hasPropertyAccesses = calls.some((call) => !call.arguments);

if (hasMethodCalls && hasPropertyAccesses) {
return [property, calls.filter((call) => call.arguments)];
}

return [property, calls];
})
);
};

export class UnexpectedCalls extends Error {
constructor(unexpectedCalls: CallMap, expectations: Expectation[]) {
const printedCalls = Array.from(unexpectedCalls.entries())
const printedCalls = Array.from(mergeCalls(unexpectedCalls).entries())
.map(([property, calls]) =>
calls
.map((call) =>
Expand Down
10 changes: 9 additions & 1 deletion tests/errors.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,15 @@ foobar`

const error = new UnexpectedCalls(
new Map([
['foo', [{ arguments: [1, 2, 3] }, { arguments: [4, 5, 6] }]],
[
'foo',
[
{ arguments: undefined },
{ arguments: [1, 2, 3] },
{ arguments: undefined },
{ arguments: [4, 5, 6] },
],
],
['bar', [{ arguments: undefined }]],
]) as CallMap,
[e1, e2]
Expand Down

0 comments on commit ff8636c

Please sign in to comment.