diff --git a/packages/jest-mock/src/__tests__/jest_mock.test.js b/packages/jest-mock/src/__tests__/jest_mock.test.js index dcb90efd9d5e..08d369a2b791 100644 --- a/packages/jest-mock/src/__tests__/jest_mock.test.js +++ b/packages/jest-mock/src/__tests__/jest_mock.test.js @@ -69,14 +69,22 @@ describe('moduleMocker', () => { }); it('escapes illegal characters in function name property', () => { - const foo = { - 'foo-bar': () => {}, - }; + function getMockFnWithOriginalName(name) { + const fn = () => {}; + Object.defineProperty(fn, 'name', {value: name}); - const mock = moduleMocker.generateFromMetadata( - moduleMocker.getMetadata(foo['foo-bar']), - ); - expect(!mock.name || mock.name === 'foo$bar').toBeTruthy(); + return moduleMocker.generateFromMetadata(moduleMocker.getMetadata(fn)); + } + + expect( + getMockFnWithOriginalName('foo-bar').name === 'foo$bar', + ).toBeTruthy(); + expect( + getMockFnWithOriginalName('foo/bar').name === 'foo$bar', + ).toBeTruthy(); + expect( + getMockFnWithOriginalName('foo𠮷bar').name === 'foo𠮷bar', + ).toBeTruthy(); }); it('special cases the mockConstructor name', () => { diff --git a/packages/jest-mock/src/index.js b/packages/jest-mock/src/index.js index 5f93868c173b..0712f4551991 100644 --- a/packages/jest-mock/src/index.js +++ b/packages/jest-mock/src/index.js @@ -37,6 +37,8 @@ type MockFunctionConfig = { const MOCK_CONSTRUCTOR_NAME = 'mockConstructor'; +const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/g; + // $FlowFixMe const RESERVED_KEYWORDS = Object.assign(Object.create(null), { arguments: true, @@ -474,8 +476,8 @@ class ModuleMockerClass { // It's also a syntax error to define a function with a reserved character // as part of it's name. - if (/[\s-]/.test(name)) { - name = name.replace(/[\s-]/g, '$'); + if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) { + name = name.replace(FUNCTION_NAME_RESERVED_PATTERN, '$'); } const body =