Skip to content

Commit

Permalink
[jest-mock] fix function name cleaning when making mock fn (#4464)
Browse files Browse the repository at this point in the history
  • Loading branch information
jsdf authored and cpojer committed Sep 12, 2017
1 parent 213634d commit 19b5cce
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
22 changes: 15 additions & 7 deletions packages/jest-mock/src/__tests__/jest_mock.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
6 changes: 4 additions & 2 deletions packages/jest-mock/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 =
Expand Down

0 comments on commit 19b5cce

Please sign in to comment.