Skip to content

Commit

Permalink
Merge pull request #4 from lucasfcosta/fix-ie-function-name
Browse files Browse the repository at this point in the history
fix: Function.name failing IE tests
  • Loading branch information
keithamus committed Jun 2, 2016
2 parents 8dac349 + 3919a90 commit b61892d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
32 changes: 30 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,34 @@ function compatibleMessage(thrown, errMatcher) {
return false;
}

/**
* ### .getFunctionName(constructorFn)
*
* Returns the name of a function.
* This also includes a polyfill function if `constructorFn.name` is not defined.
*
* @name getFunctionName
* @param {Function} constructorFn
* @namespace Utils
* @api private
*/

var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/;
function getFunctionName(constructorFn) {
var name = '';
if (typeof constructorFn.name === 'undefined') {
// Here we run a polyfill if constructorFn.name is not defined
var match = String(constructorFn).match(functionNameMatch);
if (match) {
name = match[1];
}
} else {
name = constructorFn.name;
}

return name;
}

/**
* ### .getConstructorName(errorLike)
*
Expand All @@ -99,10 +127,10 @@ function compatibleMessage(thrown, errMatcher) {
function getConstructorName(errorLike) {
var constructorName = errorLike;
if (errorLike instanceof Error) {
constructorName = errorLike.constructor.name;
constructorName = getFunctionName(errorLike.constructor);
} else if (typeof errorLike === 'function') {
// if `err` is not an instance of Error it is an error constructor itself
constructorName = new errorLike().name; // eslint-disable-line new-cap
constructorName = getFunctionName(errorLike);
}

return constructorName;
Expand Down
12 changes: 12 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,18 @@ describe('checkError', function () {

assert(checkError.getConstructorName(null) === null);
assert(checkError.getConstructorName(undefined) === undefined);

// Asserting that `getFunctionName` behaves correctly
function /*one*/correctName/*two*/() { // eslint-disable-line no-inline-comments, spaced-comment
return 0;
}

function withoutComments() {
return 1;
}

assert(checkError.getConstructorName(correctName) === 'correctName');
assert(checkError.getConstructorName(withoutComments) === 'withoutComments');
});

it('getMessage', function () {
Expand Down

0 comments on commit b61892d

Please sign in to comment.