Skip to content

Commit b61892d

Browse files
committed
Merge pull request #4 from lucasfcosta/fix-ie-function-name
fix: Function.name failing IE tests
2 parents 8dac349 + 3919a90 commit b61892d

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

index.js

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,34 @@ function compatibleMessage(thrown, errMatcher) {
8585
return false;
8686
}
8787

88+
/**
89+
* ### .getFunctionName(constructorFn)
90+
*
91+
* Returns the name of a function.
92+
* This also includes a polyfill function if `constructorFn.name` is not defined.
93+
*
94+
* @name getFunctionName
95+
* @param {Function} constructorFn
96+
* @namespace Utils
97+
* @api private
98+
*/
99+
100+
var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\(\/]+)/;
101+
function getFunctionName(constructorFn) {
102+
var name = '';
103+
if (typeof constructorFn.name === 'undefined') {
104+
// Here we run a polyfill if constructorFn.name is not defined
105+
var match = String(constructorFn).match(functionNameMatch);
106+
if (match) {
107+
name = match[1];
108+
}
109+
} else {
110+
name = constructorFn.name;
111+
}
112+
113+
return name;
114+
}
115+
88116
/**
89117
* ### .getConstructorName(errorLike)
90118
*
@@ -99,10 +127,10 @@ function compatibleMessage(thrown, errMatcher) {
99127
function getConstructorName(errorLike) {
100128
var constructorName = errorLike;
101129
if (errorLike instanceof Error) {
102-
constructorName = errorLike.constructor.name;
130+
constructorName = getFunctionName(errorLike.constructor);
103131
} else if (typeof errorLike === 'function') {
104132
// if `err` is not an instance of Error it is an error constructor itself
105-
constructorName = new errorLike().name; // eslint-disable-line new-cap
133+
constructorName = getFunctionName(errorLike);
106134
}
107135

108136
return constructorName;

test/index.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,18 @@ describe('checkError', function () {
7575

7676
assert(checkError.getConstructorName(null) === null);
7777
assert(checkError.getConstructorName(undefined) === undefined);
78+
79+
// Asserting that `getFunctionName` behaves correctly
80+
function /*one*/correctName/*two*/() { // eslint-disable-line no-inline-comments, spaced-comment
81+
return 0;
82+
}
83+
84+
function withoutComments() {
85+
return 1;
86+
}
87+
88+
assert(checkError.getConstructorName(correctName) === 'correctName');
89+
assert(checkError.getConstructorName(withoutComments) === 'withoutComments');
7890
});
7991

8092
it('getMessage', function () {

0 commit comments

Comments
 (0)