Socket
Socket
Sign inDemoInstall

jest-mock

Package Overview
Dependencies
16
Maintainers
6
Versions
237
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 28.0.0-alpha.5 to 28.0.0-alpha.6

195

build/index.d.ts

@@ -7,8 +7,8 @@ /**

*/
export declare type ConstructorLike = {
new (...args: Array<any>): any;
export declare type ClassLike = {
new (...args: any): any;
};
export declare type ConstructorLikeKeys<T> = {
[K in keyof T]: T[K] extends ConstructorLike ? K : never;
[K in keyof T]: T[K] extends ClassLike ? K : never;
}[keyof T];

@@ -22,7 +22,9 @@

export declare const fn: <T, Y extends unknown[]>(
implementation?: ((...args: Y) => T) | undefined,
) => Mock<T, Y>;
export declare const fn: <T extends FunctionLike = UnknownFunction>(
implementation?: T | undefined,
) => Mock<T>;
export declare type MaybeMocked<T> = T extends MethodLike
export declare type FunctionLike = (...args: any) => any;
export declare type MaybeMocked<T> = T extends FunctionLike
? MockedFunction<T>

@@ -36,6 +38,6 @@ : T extends object

) => infer R
? MockInstance<R, ConstructorParameters_2<T>>
? MockInstance<(...args: ConstructorParameters_2<T>) => R>
: T;
export declare type MaybeMockedDeep<T> = T extends MethodLike
export declare type MaybeMockedDeep<T> = T extends FunctionLike
? MockedFunctionDeep<T>

@@ -46,19 +48,25 @@ : T extends object

export declare type MethodLike = (...args: Array<any>) => any;
export declare type MethodLikeKeys<T> = {
[K in keyof T]: T[K] extends MethodLike ? K : never;
[K in keyof T]: T[K] extends FunctionLike ? K : never;
}[keyof T];
export declare interface Mock<T, Y extends Array<unknown> = Array<unknown>>
/**
* All what the internal typings need is to be sure that we have any-function.
* `FunctionLike` type ensures that and helps to constrain the type as well.
* The default of `UnknownFunction` makes sure that `any`s do not leak to the
* user side. For instance, calling `fn()` without implementation will return
* a mock of `(...args: Array<unknown>) => unknown` type. If implementation
* is provided, its typings are inferred correctly.
*/
export declare interface Mock<T extends FunctionLike = UnknownFunction>
extends Function,
MockInstance<T, Y> {
new (...args: Y): T;
(...args: Y): T;
MockInstance<T> {
new (...args: Parameters<T>): ReturnType<T>;
(...args: Parameters<T>): ReturnType<T>;
}
export declare type Mocked<T> = {
[P in keyof T]: T[P] extends MethodLike
? MockInstance<ReturnType<T[P]>, Parameters<T[P]>>
: T[P] extends ConstructorLike
[P in keyof T]: T[P] extends FunctionLike
? MockInstance<T[P]>
: T[P] extends ClassLike
? MockedClass<T[P]>

@@ -73,5 +81,4 @@ : T[P];

export declare type MockedClass<T extends ConstructorLike> = MockInstance<
InstanceType<T>,
T extends new (...args: infer P) => any ? P : never
export declare type MockedClass<T extends ClassLike> = MockInstance<
(args: T extends new (...args: infer P) => any ? P : never) => InstanceType<T>
> & {

@@ -85,11 +92,11 @@ prototype: T extends {

export declare type MockedFunction<T extends MethodLike> = MockWithArgs<T> & {
export declare type MockedFunction<T extends FunctionLike> = MockWithArgs<T> & {
[K in keyof T]: T[K];
};
export declare type MockedFunctionDeep<T extends MethodLike> = MockWithArgs<T> &
MockedObjectDeep<T>;
export declare type MockedFunctionDeep<T extends FunctionLike> =
MockWithArgs<T> & MockedObjectDeep<T>;
export declare type MockedObject<T> = MaybeMockedConstructor<T> & {
[K in MethodLikeKeys<T>]: T[K] extends MethodLike
[K in MethodLikeKeys<T>]: T[K] extends FunctionLike
? MockedFunction<T[K]>

@@ -102,3 +109,3 @@ : T[K];

export declare type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
[K in MethodLikeKeys<T>]: T[K] extends MethodLike
[K in MethodLikeKeys<T>]: T[K] extends FunctionLike
? MockedFunctionDeep<T[K]>

@@ -111,13 +118,12 @@ : T[K];

export declare type MockFunctionMetadata<
T,
Y extends Array<unknown>,
T extends UnknownFunction = UnknownFunction,
MetadataType = MockFunctionMetadataType,
> = {
ref?: number;
members?: Record<string, MockFunctionMetadata<T, Y>>;
mockImpl?: (...args: Y) => T;
members?: Record<string, MockFunctionMetadata<T>>;
mockImpl?: T;
name?: string;
refID?: number;
type?: MetadataType;
value?: T;
value?: ReturnType<T>;
length?: number;

@@ -136,3 +142,3 @@ };

declare type MockFunctionResult<T> =
declare type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
| MockFunctionResultIncomplete

@@ -152,3 +158,5 @@ | MockFunctionResultReturn<T>

declare type MockFunctionResultReturn<T> = {
declare type MockFunctionResultReturn<
T extends FunctionLike = UnknownFunction,
> = {
type: 'return';

@@ -158,3 +166,3 @@ /**

*/
value: T;
value: ReturnType<T>;
};

@@ -170,11 +178,11 @@

declare type MockFunctionState<T, Y extends Array<unknown>> = {
declare type MockFunctionState<T extends FunctionLike = UnknownFunction> = {
/**
* List of the call arguments of all calls that have been made to the mock.
*/
calls: Array<Y>;
calls: Array<Parameters<T>>;
/**
* List of all the object instances that have been instantiated from the mock.
*/
instances: Array<T>;
instances: Array<ReturnType<T>>;
/**

@@ -189,3 +197,3 @@ * List of the call order indexes of the mock. Jest is indexing the order of

*/
lastCall?: Y;
lastCall?: Parameters<T>;
/**

@@ -197,25 +205,27 @@ * List of the results of all calls that have been made to the mock.

export declare interface MockInstance<T, Y extends Array<unknown>> {
export declare interface MockInstance<
T extends FunctionLike = UnknownFunction,
> {
_isMockFunction: true;
_protoImpl: Function;
getMockImplementation(): ((...args: Y) => T) | undefined;
getMockImplementation(): T | undefined;
getMockName(): string;
mock: MockFunctionState<T, Y>;
mock: MockFunctionState<T>;
mockClear(): this;
mockReset(): this;
mockRestore(): void;
mockImplementation(fn: (...args: Y) => T): this;
mockImplementationOnce(fn: (...args: Y) => T): this;
mockImplementation(fn: T): this;
mockImplementationOnce(fn: T): this;
mockName(name: string): this;
mockReturnThis(): this;
mockReturnValue(value: T): this;
mockReturnValueOnce(value: T): this;
mockResolvedValue(value: Unpromisify<T>): this;
mockResolvedValueOnce(value: Unpromisify<T>): this;
mockRejectedValue(value: unknown): this;
mockRejectedValueOnce(value: unknown): this;
mockReturnValue(value: ReturnType<T>): this;
mockReturnValueOnce(value: ReturnType<T>): this;
mockResolvedValue(value: ResolveType<T>): this;
mockResolvedValueOnce(value: ResolveType<T>): this;
mockRejectedValue(value: RejectType<T>): this;
mockRejectedValueOnce(value: RejectType<T>): this;
}
export declare interface MockWithArgs<T extends MethodLike>
extends MockInstance<ReturnType<T>, Parameters<T>> {
export declare interface MockWithArgs<T extends FunctionLike>
extends MockInstance<T> {
new (...args: ConstructorParameters_2<T>): T;

@@ -247,8 +257,8 @@ (...args: Parameters<T>): ReturnType<T>;

* @see README.md
* @param _metadata Metadata for the mock in the schema returned by the
* @param metadata Metadata for the mock in the schema returned by the
* getMetadata method of this module.
*/
generateFromMetadata<T, Y extends Array<unknown>>(
_metadata: MockFunctionMetadata<T, Y>,
): Mock<T, Y>;
generateFromMetadata<T extends UnknownFunction>(
metadata: MockFunctionMetadata<T>,
): Mock<T>;
/**

@@ -258,19 +268,14 @@ * @see README.md

*/
getMetadata<T, Y extends Array<unknown>>(
component: T,
_refs?: Map<T, number>,
): MockFunctionMetadata<T, Y> | null;
isMockFunction<T, Y extends Array<unknown> = Array<unknown>>(
fn: Mock<T, Y>,
): fn is Mock<T, Y>;
isMockFunction<T, Y extends Array<unknown> = Array<unknown>>(
fn: SpyInstance<T, Y>,
): fn is SpyInstance<T, Y>;
isMockFunction<T, Y extends Array<unknown> = Array<unknown>>(
fn: (...args: Y) => T,
): fn is Mock<T, Y>;
isMockFunction(fn: unknown): fn is Mock<unknown>;
fn<T, Y extends Array<unknown>>(
implementation?: (...args: Y) => T,
): Mock<T, Y>;
getMetadata<T extends UnknownFunction>(
component: ReturnType<T>,
_refs?: Map<ReturnType<T>, number>,
): MockFunctionMetadata<T> | null;
isMockFunction<T extends FunctionLike = UnknownFunction>(
fn: SpyInstance<T>,
): fn is SpyInstance<T>;
isMockFunction<P extends Array<unknown>, R extends unknown>(
fn: (...args: P) => R,
): fn is Mock<(...args: P) => R>;
isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
spyOn<T extends object, M extends PropertyLikeKeys<T>>(

@@ -280,3 +285,3 @@ object: T,

accessType: 'get',
): SpyInstance<T[M], []>;
): SpyInstance<() => T[M]>;
spyOn<T extends object, M extends PropertyLikeKeys<T>>(

@@ -286,8 +291,10 @@ object: T,

accessType: 'set',
): SpyInstance<void, [T[M]]>;
): SpyInstance<(arg: T[M]) => void>;
spyOn<T extends object, M extends ConstructorLikeKeys<T>>(
object: T,
methodName: M,
): T[M] extends ConstructorLike
? SpyInstance<InstanceType<T[M]>, ConstructorParameters_2<T[M]>>
): T[M] extends ClassLike
? SpyInstance<
(...args: ConstructorParameters_2<T[M]>) => InstanceType<T[M]>
>
: never;

@@ -297,4 +304,4 @@ spyOn<T extends object, M extends MethodLikeKeys<T>>(

methodName: M,
): T[M] extends MethodLike
? SpyInstance<ReturnType<T[M]>, Parameters<T[M]>>
): T[M] extends FunctionLike
? SpyInstance<(...args: Parameters<T[M]>) => ReturnType<T[M]>>
: never;

@@ -311,5 +318,5 @@ private _spyOnProperty;

export declare type PropertyLikeKeys<T> = {
[K in keyof T]: T[K] extends MethodLike
[K in keyof T]: T[K] extends FunctionLike
? never
: T[K] extends ConstructorLike
: T[K] extends ClassLike
? never

@@ -319,5 +326,11 @@ : K;

export declare interface SpyInstance<T, Y extends Array<unknown>>
extends MockInstance<T, Y> {}
declare type RejectType<T extends FunctionLike> =
ReturnType<T> extends PromiseLike<any> ? unknown : never;
declare type ResolveType<T extends FunctionLike> =
ReturnType<T> extends PromiseLike<infer U> ? U : never;
export declare interface SpyInstance<T extends FunctionLike = UnknownFunction>
extends MockInstance<T> {}
declare const spyOn_2: {

@@ -328,3 +341,3 @@ <T extends object, M extends PropertyLikeKeys<T>>(

accessType: 'get',
): SpyInstance<T[M], []>;
): SpyInstance<() => T[M]>;
<T_1 extends object, M_1 extends PropertyLikeKeys<T_1>>(

@@ -334,8 +347,10 @@ object: T_1,

accessType: 'set',
): SpyInstance<void, [T_1[M_1]]>;
): SpyInstance<(arg: T_1[M_1]) => void>;
<T_2 extends object, M_2 extends ConstructorLikeKeys<T_2>>(
object: T_2,
methodName: M_2,
): T_2[M_2] extends ConstructorLike
? SpyInstance<InstanceType<T_2[M_2]>, ConstructorParameters_2<T_2[M_2]>>
): T_2[M_2] extends ClassLike
? SpyInstance<
(...args: ConstructorParameters_2<T_2[M_2]>) => InstanceType<T_2[M_2]>
>
: never;

@@ -345,4 +360,4 @@ <T_3 extends object, M_3 extends MethodLikeKeys<T_3>>(

methodName: M_3,
): T_3[M_3] extends MethodLike
? SpyInstance<ReturnType<T_3[M_3]>, Parameters<T_3[M_3]>>
): T_3[M_3] extends FunctionLike
? SpyInstance<(...args: Parameters<T_3[M_3]>) => ReturnType<T_3[M_3]>>
: never;

@@ -352,4 +367,4 @@ };

declare type Unpromisify<T> = T extends Promise<infer R> ? R : never;
declare type UnknownFunction = (...args: Array<unknown>) => unknown;
export {};

@@ -18,4 +18,11 @@ 'use strict';

// https://www.typescriptlang.org/docs/handbook/utility-types.html#constructorparameterstype
// TODO Replace with Awaited utility type when minimum supported TS version will be 4.5 or above
//https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html#the-awaited-type-and-promise-improvements
/**
* All what the internal typings need is to be sure that we have any-function.
* `FunctionLike` type ensures that and helps to constrain the type as well.
* The default of `UnknownFunction` makes sure that `any`s do not leak to the
* user side. For instance, calling `fn()` without implementation will return
* a mock of `(...args: Array<unknown>) => unknown` type. If implementation
* is provided, its typings are inferred correctly.
*/
const MOCK_CONSTRUCTOR_NAME = 'mockConstructor';

@@ -556,3 +563,3 @@ const FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/;

const unknownType = metadata.type || 'undefined type';
throw new Error('Unrecognized type ' + unknownType);
throw new Error(`Unrecognized type ${unknownType}`);
}

@@ -590,3 +597,3 @@ }

) {
name = '$' + name;
name = `$${name}`;
} // It's also a syntax error to define a function with a reserved character

@@ -600,10 +607,5 @@ // as part of it's name.

const body =
'return function ' +
name +
'() {' +
'return ' +
MOCK_CONSTRUCTOR_NAME +
'.apply(this,arguments);' +
'}' +
bindCall;
`return function ${name}() {` +
` return ${MOCK_CONSTRUCTOR_NAME}.apply(this,arguments);` +
`}${bindCall}`;
const createConstructor = new this._environmentGlobal.Function(

@@ -653,11 +655,11 @@ MOCK_CONSTRUCTOR_NAME,

* @see README.md
* @param _metadata Metadata for the mock in the schema returned by the
* @param metadata Metadata for the mock in the schema returned by the
* getMetadata method of this module.
*/
generateFromMetadata(_metadata) {
generateFromMetadata(metadata) {
const callbacks = [];
const refs = {};
const mock = this._generateMock(_metadata, callbacks, refs);
const mock = this._generateMock(metadata, callbacks, refs);

@@ -701,7 +703,6 @@ callbacks.forEach(setter => setter());

} else if (type === 'function') {
// @ts-expect-error this is a function so it has a name
metadata.name = component.name; // @ts-expect-error may be a mock
// @ts-expect-error component is a function so it has a name
metadata.name = component.name;
if (component._isMockFunction === true) {
// @ts-expect-error may be a mock
if (this.isMockFunction(component)) {
metadata.mockImpl = component.getMockImplementation();

@@ -716,6 +717,7 @@ }

if (type !== 'array') {
// @ts-expect-error component is object
this._getSlots(component).forEach(slot => {
if (
type === 'function' && // @ts-expect-error may be a mock
component._isMockFunction === true &&
type === 'function' &&
this.isMockFunction(component) &&
slot.match(/^mock/)

@@ -746,3 +748,3 @@ ) {

isMockFunction(fn) {
return !!fn && fn._isMockFunction === true;
return fn != null && fn._isMockFunction === true;
}

@@ -773,3 +775,3 @@

throw new Error(
'Cannot spyOn on a primitive value; ' + this._typeOf(object) + ' given'
`Cannot spyOn on a primitive value; ${this._typeOf(object)} given`
);

@@ -783,7 +785,5 @@ }

throw new Error(
'Cannot spy the ' +
methodName +
' property because it is not a function; ' +
this._typeOf(original) +
' given instead'
`Cannot spy the ${methodName} property because it is not a function; ${this._typeOf(
original
)} given instead`
);

@@ -849,3 +849,3 @@ }

throw new Error(
'Cannot spyOn on a primitive value; ' + this._typeOf(obj) + ' given'
`Cannot spyOn on a primitive value; ${this._typeOf(obj)} given`
);

@@ -856,3 +856,3 @@ }

throw new Error(
'spyOn could not find an object to spy upon for ' + propertyName + ''
`spyOn could not find an object to spy upon for ${propertyName}`
);

@@ -874,7 +874,7 @@ }

if (!descriptor) {
throw new Error(propertyName + ' property does not exist');
throw new Error(`${propertyName} property does not exist`);
}
if (!descriptor.configurable) {
throw new Error(propertyName + ' is not declared configurable');
throw new Error(`${propertyName} is not declared configurable`);
}

@@ -884,3 +884,3 @@

throw new Error(
'Property ' + propertyName + ' does not have access type ' + accessType
`Property ${propertyName} does not have access type ${accessType}`
);

@@ -894,9 +894,7 @@ }

throw new Error(
'Cannot spy the ' +
propertyName +
' property because it is not a function; ' +
this._typeOf(original) +
' given instead'
`Cannot spy the ${propertyName} property because it is not a function; ${this._typeOf(
original
)} given instead`
);
} // @ts-expect-error: mock is assignable
}

@@ -939,3 +937,3 @@ descriptor[accessType] = this._makeComponent(

_typeOf(value) {
return value == null ? '' + value : typeof value;
return value == null ? `${value}` : typeof value;
} // the typings test helper

@@ -942,0 +940,0 @@

{
"name": "jest-mock",
"version": "28.0.0-alpha.5",
"version": "28.0.0-alpha.6",
"repository": {

@@ -20,3 +20,3 @@ "type": "git",

"dependencies": {
"@jest/types": "^28.0.0-alpha.5",
"@jest/types": "^28.0.0-alpha.6",
"@types/node": "*"

@@ -34,3 +34,3 @@ },

},
"gitHead": "46fb19b2628bd87676c10730ba19592c30b05478"
"gitHead": "6284ada4adb7008f5f8673b1a7b1c789d2e508fb"
}
# jest-mock
**Note:** More details on user side API can be found in [Jest documentation](https://jestjs.io/docs/mock-function-api).
## API

@@ -15,3 +17,3 @@

Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the getMetadata method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn` in this module.
Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the `getMetadata()` method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn()` in this module.

@@ -60,5 +62,5 @@ One important note: function prototypes are handled specially by this mocking framework. For functions with prototypes, when called as a constructor, the mock will install mocked function members on the instance. This allows different instances of the same constructor to have different values for its mocks member and its return values.

defines an object with a slot named `self` that refers back to the object.
Defines an object with a slot named `self` that refers back to the object.
### `fn`
### `fn(implementation?)`

@@ -89,7 +91,13 @@ Generates a stand-alone function with members that help drive unit tests or confirm expectations. Specifically, functions returned by this method have the following members:

Syntactic sugar for .mockImplementation(function() {return this;})
Syntactic sugar for:
In case both `mockImplementationOnce()/mockImplementation()` and `mockReturnValueOnce()/mockReturnValue()` are called. The priority of which to use is based on what is the last call:
```js
mockFn.mockImplementation(function () {
return this;
});
```
- if the last call is mockReturnValueOnce() or mockReturnValue(), use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try mockImplementation();
- if the last call is mockImplementationOnce() or mockImplementation(), run the specific implementation and return the result or run default implementation and return the result.
In case both `.mockImplementationOnce()` / `.mockImplementation()` and `.mockReturnValueOnce()` / `.mockReturnValue()` are called. The priority of which to use is based on what is the last call:
- if the last call is `.mockReturnValueOnce()` or `.mockReturnValue()`, use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try `.mockImplementation()`;
- if the last call is `.mockImplementationOnce()` or `.mockImplementation()`, run the specific implementation and return the result or run default implementation and return the result.
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc