Skip to content

Commit

Permalink
Added proper formatting of unexpeted function call error
Browse files Browse the repository at this point in the history
  • Loading branch information
kcwiakala committed Dec 4, 2017
1 parent 9c9e4a9 commit 5574b94
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
34 changes: 32 additions & 2 deletions lib/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,36 @@ const check = require('./check');

class UnexpectedCall extends Error {};

function formatArgument(arg) {
switch(typeof arg) {
case 'string':
return '"' + arg + '"';
case 'function':
return 'function';
case 'number':
case 'boolean':
case 'undefined':
return '' + arg;
case 'object':
if(arg === null) {
return 'null';
} else if(_.isArray(arg)) {
return '[...]';
}
return '{...}';
}
}

function formatCall(functionName, args) {
let output = functionName + '(';
let formattedArgs = [];
for(let i in args) {
formattedArgs.push(formatArgument(args[i]));
}
output += formattedArgs.join(',') + ')';
return output;
}

/** @class Mock
*
*/
Expand Down Expand Up @@ -38,11 +68,11 @@ class Mock {
const args = Array.from(arguments).slice(1);
const expectations = this.expectations[functionName];
if(!expectations || expectations.length === 0) {
throw new UnexpectedCall('Unexpected call of ' + functionName);
throw new UnexpectedCall('Unexpected call of ' + formatCall(functionName, args));
}
const idx = _.findIndex(expectations, exp => exp.isMatching(args) && !exp.isSaturated());
if(idx < 0) {
throw new UnexpectedCall('No matching expectation for call ' + functionName + '(' + args.join(',') + ')' );
throw new UnexpectedCall('No matching expectation for call ' + formatCall(functionName, args));
} else {
return expectations[idx].execute(args);
}
Expand Down
7 changes: 7 additions & 0 deletions test/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ describe('Mock', () => {
expect(a.foo(1,2)).to.be.equal(4);
expect(a.foo.bind(a, 2, 1)).to.throw(UnexpectedCall, 'No matching expectation');
});

it('Should throw exception with proper formatting of failed call', () => {
let a = new A();
let aMock = new Mock(a);
expect(() => a.foo('Hello', {x:1, y:2}, [1,2,3], false)).to.throw(UnexpectedCall, 'foo("Hello",{...},[...],false)');
expect(() => a.bar(1.23, null, undefined, a.bar)).to.throw(UnexpectedCall, 'bar(1.23,null,undefined,function)');
});
});

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

0 comments on commit 5574b94

Please sign in to comment.