Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix getting function name for rare cases #8362

Merged
merged 2 commits into from Apr 23, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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