This commit is contained in:
2026-08-14 16:03:47 +01:00
parent fd53e3f4fb
commit dfdc3b2840
2463 changed files with 186456 additions and 111315 deletions
+5 -1
View File
@@ -1,3 +1,7 @@
# @vitest/spy
Lightweight Jest compatible spy implementation.
[![NPM version](https://img.shields.io/npm/v/@vitest/spy?color=a1b858&label=)](https://npmx.dev/package/@vitest/spy)
Lightweight Jest-compatible mocking implementation.
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/spy) | [Documentation](https://vitest.dev/api/mock)
+38 -6
View File
@@ -1,3 +1,5 @@
import { Disposable } from '@vitest/spy/optional-types.js';
interface MockResultReturn<T> {
type: "return";
/**
@@ -31,7 +33,7 @@ interface MockSettledResultRejected {
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
type MockSettledResult<T> = MockSettledResultFulfilled<T> | MockSettledResultRejected | MockSettledResultIncomplete;
type MockParameters<T extends Procedure | Constructable> = T extends Constructable ? ConstructorParameters<T> : T extends Procedure ? Parameters<T> : never;
type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? void : T extends Procedure ? ReturnType<T> : never;
type MockReturnType<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : T extends Procedure ? ReturnType<T> : never;
type MockProcedureContext<T extends Procedure | Constructable> = T extends Constructable ? InstanceType<T> : ThisParameterType<T>;
interface MockContext<T extends Procedure | Constructable = Procedure> {
/**
@@ -173,7 +175,7 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
/**
* Clears all information about every call. After calling it, all properties on `.mock` will return to their initial state. This method does not reset implementations. It is useful for cleaning up mocks between different assertions.
*
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/#clearmocks) setting in the configuration.
* To automatically call this method before each test, enable the [`clearMocks`](https://vitest.dev/config/clearmocks) setting in the configuration.
* @see https://vitest.dev/api/mock#mockclear
*/
mockClear(): this;
@@ -183,7 +185,7 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
* Note that resetting a mock from `vi.fn()` will set implementation to an empty function that returns `undefined`.
* Resetting a mock from `vi.fn(impl)` will set implementation to `impl`. It is useful for completely resetting a mock to its default state.
*
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/#mockreset) setting in the configuration.
* To automatically call this method before each test, enable the [`mockReset`](https://vitest.dev/config/mockreset) setting in the configuration.
* @see https://vitest.dev/api/mock#mockreset
*/
mockReset(): this;
@@ -267,6 +269,28 @@ interface MockInstance<T extends Procedure | Constructable = Procedure> extends
*/
mockReturnValueOnce(value: MockReturnType<T>): this;
/**
* Accepts a value that will be thrown whenever the mock function is called.
* @see https://vitest.dev/api/mock#mockthrow
* @example
* const myMockFn = vi.fn().mockThrow(new Error('error'))
* myMockFn() // throws 'error'
*/
mockThrow(value: unknown): this;
/**
* Accepts a value that will be thrown during the next function call. If chained, every consecutive call will throw the specified value.
* @example
* const myMockFn = vi
* .fn()
* .mockReturnValue('default')
* .mockThrowOnce(new Error('first call error'))
* .mockThrowOnce('second call error')
*
* expect(() => myMockFn()).toThrowError('first call error')
* expect(() => myMockFn()).toThrowError('second call error')
* expect(myMockFn()).toEqual('default')
*/
mockThrowOnce(value: unknown): this;
/**
* Accepts a value that will be resolved when the async function is called. TypeScript will only accept values that match the return type of the original function.
* @example
* const asyncMock = vi.fn().mockResolvedValue(42)
@@ -322,11 +346,19 @@ type PartialResultFunction<T> = T extends Constructable ? ({
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
}) : T extends Procedure ? (...args: Parameters<T>) => PartialMaybePromise<ReturnType<T>> : T;
type PartialMock<T extends Procedure | Constructable = Procedure> = Mock<PartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
type DeepPartial<T> = T extends Procedure ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends object ? { [K in keyof T]? : DeepPartial<T[K]> } : T;
type DeepPartialMaybePromise<T> = T extends Promise<Awaited<T>> ? Promise<DeepPartial<Awaited<T>>> : DeepPartial<T>;
type DeepPartialResultFunction<T> = T extends Constructable ? ({
new (...args: ConstructorParameters<T>): InstanceType<T>;
}) | ({
(this: InstanceType<T>, ...args: ConstructorParameters<T>): void;
}) : T extends Procedure ? (...args: Parameters<T>) => DeepPartialMaybePromise<ReturnType<T>> : T;
type DeepPartialMock<T extends Procedure | Constructable = Procedure> = Mock<DeepPartialResultFunction<T extends Mock ? NonNullable<ReturnType<T["getMockImplementation"]>> : T>>;
type MaybeMockedConstructor<T> = T extends Constructable ? Mock<T> : T;
type MockedFunction<T extends Procedure | Constructable> = Mock<T> & { [K in keyof T] : T[K] };
type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & { [K in keyof T] : T[K] };
type MockedFunction<T extends Procedure | Constructable> = Mock<T> & MockedObject<T>;
type PartiallyMockedFunction<T extends Procedure | Constructable> = PartialMock<T> & MockedObject<T>;
type MockedFunctionDeep<T extends Procedure | Constructable> = Mock<T> & MockedObjectDeep<T>;
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = PartialMock<T> & MockedObjectDeep<T>;
type PartiallyMockedFunctionDeep<T extends Procedure | Constructable> = DeepPartialMock<T> & MockedObjectDeep<T>;
type MockedObject<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunction<T[K]> : T[K] } & { [K in Properties<T>] : T[K] };
type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in Methods<T>] : T[K] extends Procedure ? MockedFunctionDeep<T[K]> : T[K] } & { [K in Properties<T>] : MaybeMockedDeep<T[K]> };
type MaybeMockedDeep<T> = T extends Procedure | Constructable ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
+72 -22
View File
@@ -8,7 +8,6 @@ const MOCK_RESTORE = new Set();
const REGISTERED_MOCKS = new Set();
const MOCK_CONFIGS = new WeakMap();
function createMockInstance(options = {}) {
var _ref;
const { originalImplementation, restore, mockImplementation, resetToMockImplementation, resetToMockName } = options;
if (restore) {
MOCK_RESTORE.add(restore);
@@ -20,7 +19,7 @@ function createMockInstance(options = {}) {
state,
...options
});
const mockLength = ((_ref = mockImplementation || originalImplementation) === null || _ref === void 0 ? void 0 : _ref.length) ?? 0;
const mockLength = (mockImplementation || originalImplementation)?.length ?? 0;
Object.defineProperty(mock, "length", {
writable: true,
enumerable: false,
@@ -65,7 +64,7 @@ function createMockInstance(options = {}) {
config.mockImplementation = implementation;
config.onceMockImplementations = [];
const returnValue = callback();
if (typeof returnValue === "object" && typeof (returnValue === null || returnValue === void 0 ? void 0 : returnValue.then) === "function") {
if (typeof returnValue === "object" && typeof returnValue?.then === "function") {
return returnValue.then(() => {
reset();
return mock;
@@ -81,22 +80,64 @@ function createMockInstance(options = {}) {
});
};
mock.mockReturnValue = function mockReturnValue(value) {
return mock.mockImplementation(() => value);
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockReturnValue");
}
return value;
});
};
mock.mockReturnValueOnce = function mockReturnValueOnce(value) {
return mock.mockImplementationOnce(() => value);
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockReturnValueOnce");
}
return value;
});
};
mock.mockThrow = function mockThrow(value) {
// eslint-disable-next-line prefer-arrow-callback
return mock.mockImplementation(function() {
throw value;
});
};
mock.mockThrowOnce = function mockThrowOnce(value) {
// eslint-disable-next-line prefer-arrow-callback
return mock.mockImplementationOnce(function() {
throw value;
});
};
mock.mockResolvedValue = function mockResolvedValue(value) {
return mock.mockImplementation(() => Promise.resolve(value));
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockResolvedValue");
}
return Promise.resolve(value);
});
};
mock.mockResolvedValueOnce = function mockResolvedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.resolve(value));
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockResolvedValueOnce");
}
return Promise.resolve(value);
});
};
mock.mockRejectedValue = function mockRejectedValue(value) {
return mock.mockImplementation(() => Promise.reject(value));
return mock.mockImplementation(function() {
if (new.target) {
throwConstructorError("mockRejectedValue");
}
return Promise.reject(value);
});
};
mock.mockRejectedValueOnce = function mockRejectedValueOnce(value) {
return mock.mockImplementationOnce(() => Promise.reject(value));
return mock.mockImplementationOnce(function() {
if (new.target) {
throwConstructorError("mockRejectedValueOnce");
}
return Promise.reject(value);
});
};
mock.mockClear = function mockClear() {
state.calls = [];
@@ -116,7 +157,7 @@ function createMockInstance(options = {}) {
};
mock.mockRestore = function mockRestore() {
mock.mockReset();
return restore === null || restore === void 0 ? void 0 : restore();
return restore?.();
};
mock.mockName = function mockName(name) {
if (typeof name === "string") {
@@ -137,7 +178,7 @@ function createMockInstance(options = {}) {
}
function fn(originalImplementation) {
// if the function is already a mock, just return the same function,
// simillarly to how vi.spyOn() works
// similarly to how vi.spyOn() works
if (originalImplementation != null && isMockFunction(originalImplementation)) {
return originalImplementation;
}
@@ -161,6 +202,12 @@ function spyOn(object, key, accessor) {
let original;
if (originalDescriptor) {
original = originalDescriptor[accessType];
// weird Proxy edge case where descriptor's value is undefined,
// but there's still a value on the object when called
// https://github.com/vitest-dev/vitest/issues/9439
if (original == null && accessType === "value") {
original = object[key];
}
} else if (accessType !== "value") {
original = () => object[key];
} else {
@@ -236,7 +283,7 @@ let invocationCallCounter = 1;
function createMock({ state, config, name: mockName, prototypeState, prototypeConfig, keepMembersImplementation, mockImplementation, prototypeMembers = [] }) {
const original = config.mockOriginal;
const pseudoOriginal = mockImplementation;
const name = mockName || (original === null || original === void 0 ? void 0 : original.name) || "Mock";
const name = mockName || original?.name || "Mock";
const namedObject = { [name]: (function(...args) {
registerCalls(args, state, prototypeState);
registerInvocationOrder(invocationCallCounter++, state, prototypeState);
@@ -253,7 +300,7 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
const context = new.target ? undefined : this;
const [instanceIndex, instancePrototypeIndex] = registerInstance(context, state, prototypeState);
const [contextIndex, contextPrototypeIndex] = registerContext(context, state, prototypeState);
const implementation = config.onceMockImplementations.shift() || config.mockImplementation || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.onceMockImplementations.shift()) || (prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockImplementation) || original || function() {};
const implementation = config.onceMockImplementations.shift() || config.mockImplementation || prototypeConfig?.onceMockImplementations.shift() || prototypeConfig?.mockImplementation || original || function() {};
let returnValue;
let thrownValue;
let didThrow = false;
@@ -262,11 +309,11 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
returnValue = Reflect.construct(implementation, args, new.target);
// jest calls this before the implementation, but we have to resolve this _after_
// because we cannot do it before the `Reflect.construct` called the custom implementation.
// fortunetly, the constructor is always an empty functon because `prototypeMethods`
// fortunately, the constructor is always an empty function because `prototypeMethods`
// are only used by the automocker, so this doesn't matter
for (const prop of prototypeMembers) {
const prototypeMock = returnValue[prop];
// the method was overidden because of inheritence, ignore it
// the method was overridden because of inheritance, ignore it
// eslint-disable-next-line ts/no-use-before-define
if (prototypeMock !== mock.prototype[prop]) {
continue;
@@ -275,7 +322,7 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
const prototypeState = isMock ? prototypeMock.mock : undefined;
const prototypeConfig = isMock ? MOCK_CONFIGS.get(prototypeMock) : undefined;
returnValue[prop] = createMockInstance({
originalImplementation: keepMembersImplementation ? prototypeConfig === null || prototypeConfig === void 0 ? void 0 : prototypeConfig.mockOriginal : undefined,
originalImplementation: keepMembersImplementation ? prototypeConfig?.mockOriginal : undefined,
prototypeState,
prototypeConfig,
keepMembersImplementation
@@ -335,28 +382,28 @@ function createMock({ state, config, name: mockName, prototypeState, prototypeCo
}
function registerCalls(args, state, prototypeState) {
state.calls.push(args);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.calls.push(args);
prototypeState?.calls.push(args);
}
function registerInvocationOrder(order, state, prototypeState) {
state.invocationCallOrder.push(order);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.invocationCallOrder.push(order);
prototypeState?.invocationCallOrder.push(order);
}
function registerResult(result, state, prototypeState) {
state.results.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.results.push(result);
prototypeState?.results.push(result);
}
function registerSettledResult(result, state, prototypeState) {
state.settledResults.push(result);
prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.settledResults.push(result);
prototypeState?.settledResults.push(result);
}
function registerInstance(instance, state, prototypeState) {
const instanceIndex = state.instances.push(instance);
const instancePrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.instances.push(instance);
const instancePrototypeIndex = prototypeState?.instances.push(instance);
return [instanceIndex, instancePrototypeIndex];
}
function registerContext(context, state, prototypeState) {
const contextIndex = state.contexts.push(context);
const contextPrototypeIndex = prototypeState === null || prototypeState === void 0 ? void 0 : prototypeState.contexts.push(context);
const contextPrototypeIndex = prototypeState?.contexts.push(context);
return [contextIndex, contextPrototypeIndex];
}
function copyOriginalStaticProperties(mock, original) {
@@ -429,5 +476,8 @@ function clearAllMocks() {
function resetAllMocks() {
REGISTERED_MOCKS.forEach((mock) => mock.mockReset());
}
function throwConstructorError(shorthand) {
throw new TypeError(`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`);
}
export { clearAllMocks, createMockInstance, fn, isMockFunction, resetAllMocks, restoreAllMocks, spyOn };
+6
View File
@@ -0,0 +1,6 @@
/* eslint-disable ts/ban-ts-comment */
export interface Disposable {
// @ts-ignore -- Symbol.dispose might not be in user types
[Symbol.dispose]: () => void
}
+14 -3
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/spy",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Lightweight Jest compatible spy implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/spy#readme",
"homepage": "https://vitest.dev/api/mock",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,19 +14,30 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"mock",
"spy",
"intercept"
],
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"./optional-types.js": {
"types": "./optional-types.d.ts"
},
"./*": "./*"
},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
"dist"
"dist",
"optional-types.d.ts"
],
"scripts": {
"build": "premove dist && rollup -c",