-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
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 function name sanitization in jest-mock #4464
Conversation
@@ -37,6 +37,8 @@ type MockFunctionConfig = { | |||
|
|||
const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; | |||
|
|||
const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/g; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ohh, yeah, let's fix that. Good find.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The call to .test
doesn't need the flag, but the call to .replace
does.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'll put up another PR to fix this
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh I see it's already fixed in master. Thanks for spotting this @thymikee !
This pull request has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Summary
When creating mock functions, jest-mock attempts to copy over the existing name of the function being mocked. However, it creates the mock functions using
Function()
(a form of eval), using string interpolation to specify the function name in the code being evaluated. This means that only function names consisting of valid characters for JS identifiers can be used.Currently there is some code which attempts to sanitize function names so they are valid, but it only replaces spaces and hypens. Other invalid characters remain.
I've expanded the regex used to include other special characters in the ASCII space, while leaving ASCII chars which are valid for identifiers, as well as unicode characters (for people coding in non-Latin alphabets, for example).
Test plan
I've expanded the relevant test case in
packages/jest-mock/src/__tests__/jest_mock.test.js
to include more cases. I also changed the test to usedefineProperty
to ensure the input function has a name, so the existing special case where function.name is null can be removed.