Skip to content
/ jest Public
forked from jestjs/jest

Commit

Permalink
Improve error messaging from "spyOn" (jestjs#4810)
Browse files Browse the repository at this point in the history
  • Loading branch information
mjesun authored and cpojer committed Nov 1, 2017
1 parent 0f0d3d9 commit 0e35f7c
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/jest-mock/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ class ModuleMockerClass {
}

isMockFunction(fn: any): boolean {
return !!fn._isMockFunction;
return !!(fn && fn._isMockFunction);
}

fn(implementation?: any): any {
Expand All @@ -657,12 +657,22 @@ class ModuleMockerClass {
}

spyOn(object: any, methodName: any): any {
if (typeof object !== 'object' && typeof object !== 'function') {
throw new Error(
'Cannot spyOn on a primitive value; ' + this._typeOf(object) + ' given',
);
}

const original = object[methodName];

if (!this.isMockFunction(original)) {
if (typeof original !== 'function') {
throw new Error(
'Cannot spyOn the ' + methodName + ' property; it is not a function',
'Cannot spy the ' +
methodName +
' property because it is not a function; ' +
this._typeOf(original) +
' given instead',
);
}

Expand Down Expand Up @@ -691,6 +701,10 @@ class ModuleMockerClass {
this._spyState.forEach(restore => restore());
this._spyState = new Set();
}

_typeOf(value: any): string {
return value == null ? '' + value : typeof value;
}
}

export type ModuleMocker = ModuleMockerClass;
Expand Down

0 comments on commit 0e35f7c

Please sign in to comment.