Skip to content

Commit

Permalink
Fix getting function name for rare cases (#8362)
Browse files Browse the repository at this point in the history
  • Loading branch information
Connormiha authored and SimenB committed Apr 23, 2019
1 parent 7e1e3f8 commit 20ba4be
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -21,6 +21,7 @@
- `[jest-jasmine2]` Fix describe return value warning being shown if the describe function throws ([#8335](https://github.com/facebook/jest/pull/8335))
- `[jest-environment-jsdom]` Re-declare global prototype of JSDOMEnvironment ([#8352](https://github.com/facebook/jest/pull/8352))
- `[jest-snapshot]` Handle arrays when merging snapshots ([#7089](https://github.com/facebook/jest/pull/7089))
- `[expect]` Extract names of async and generator functions ([#8362](https://github.com/facebook/jest/pull/8362))

### Chore & Maintenance

Expand Down
41 changes: 41 additions & 0 deletions packages/expect/src/__tests__/asymmetricMatchers.test.js
Expand Up @@ -42,6 +42,47 @@ test('Any.toAsymmetricMatcher()', () => {
jestExpect(any(Number).toAsymmetricMatcher()).toBe('Any<Number>');
});

test('Any.toAsymmetricMatcher() with function name', () => {
[
['someFunc', function someFunc() {}],
['$someFunc', function $someFunc() {}],
[
'$someFunc2',
(function() {
function $someFunc2() {}
Object.defineProperty($someFunc2, 'name', {value: ''});
return $someFunc2;
})(),
],
[
'$someAsyncFunc',
(function() {
async function $someAsyncFunc() {}
Object.defineProperty($someAsyncFunc, 'name', {value: ''});
return $someAsyncFunc;
})(),
],
[
'$someGeneratorFunc',
(function() {
function* $someGeneratorFunc() {}
Object.defineProperty($someGeneratorFunc, 'name', {value: ''});
return $someGeneratorFunc;
})(),
],
[
'$someFuncWithFakeToString',
(function() {
function $someFuncWithFakeToString() {}
$someFuncWithFakeToString.toString = () => 'Fake to string';
return $someFuncWithFakeToString;
})(),
],
].forEach(([name, fn]: [string, any]) => {
jestExpect(any(fn).toAsymmetricMatcher()).toBe(`Any<${name}>`);
});
});

test('Any throws when called with empty constructor', () => {
jestExpect(() => any()).toThrow();
});
Expand Down
6 changes: 5 additions & 1 deletion packages/expect/src/jasmineUtils.ts
Expand Up @@ -37,6 +37,8 @@ export function equals(
return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
}

const functionToString = Function.prototype.toString;

function isAsymmetric(obj: any) {
return !!obj && isA('Function', obj.asymmetricMatch);
}
Expand Down Expand Up @@ -258,7 +260,9 @@ export function fnNameFor(func: Function) {
return func.name;
}

const matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/);
const matches = functionToString
.call(func)
.match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
return matches ? matches[1] : '<anonymous>';
}

Expand Down

0 comments on commit 20ba4be

Please sign in to comment.