Skip to content

Commit

Permalink
fix: only set name of mocked function if string (#12674)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Apr 15, 2022
1 parent 1cce9a7 commit 719c2aa
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -78,6 +78,7 @@
- `[jest-jasmine2]` Do not set `duration` to `0` for skipped tests ([#12518](https://github.com/facebook/jest/pull/12518))
- `[jest-matcher-utils]` Pass maxWidth to `pretty-format` to avoid printing every element in arrays by default ([#12402](https://github.com/facebook/jest/pull/12402))
- `[jest-mock]` Fix function overloads for `spyOn` to allow more correct type inference in complex object ([#12442](https://github.com/facebook/jest/pull/12442))
- `[jest-mock]` Handle overridden `Function.name` property ([#12674](https://github.com/facebook/jest/pull/12674))
- `[jest-reporters]` Notifications generated by the `--notify` flag are no longer persistent in GNOME Shell. ([#11733](https://github.com/facebook/jest/pull/11733))
- `[@jest/reporters]` Move missing icon file which is needed for `NotifyReporter` class. ([#12593](https://github.com/facebook/jest/pull/12593))
- `[jest-resolver]` Call custom resolver with core node.js modules ([#12654](https://github.com/facebook/jest/pull/12654))
Expand Down
11 changes: 11 additions & 0 deletions packages/jest-mock/src/__tests__/index.test.ts
Expand Up @@ -30,6 +30,17 @@ describe('moduleMocker', () => {
expect(metadata.name).toBe('x');
});

it('does not return broken name property', () => {
class By {
static name() {
return 'this is not a name';
}
}
const metadata = moduleMocker.getMetadata(By);
expect(typeof By.name).toBe('function');
expect(metadata).not.toHaveProperty('name');
});

it('mocks constant values', () => {
const metadata = moduleMocker.getMetadata(Symbol.for('bowties.are.cool'));
expect(metadata.value).toEqual(Symbol.for('bowties.are.cool'));
Expand Down
8 changes: 6 additions & 2 deletions packages/jest-mock/src/index.ts
Expand Up @@ -971,8 +971,12 @@ export class ModuleMocker {
metadata.value = component;
return metadata;
} else if (type === 'function') {
// @ts-expect-error component is a function so it has a name
metadata.name = component.name;
// @ts-expect-error component is a function so it has a name, but not
// necessarily a string: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#function_names_in_classes
const componentName = component.name;
if (typeof componentName === 'string') {
metadata.name = componentName;
}
if (this.isMockFunction(component)) {
metadata.mockImpl = component.getMockImplementation() as T;
}
Expand Down

0 comments on commit 719c2aa

Please sign in to comment.