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
+4
View File
@@ -1,5 +1,7 @@
# @vitest/expect
[![NPM version](https://img.shields.io/npm/v/@vitest/runner?color=a1b858&label=)](https://npmx.dev/package/@vitest/runner)
Jest's expect matchers as a Chai plugin.
## Usage
@@ -19,3 +21,5 @@ chai.use(JestChaiExpect)
// adds asymmetric matchers like stringContaining, objectContaining
chai.use(JestAsymmetricMatchers)
```
[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/expect) | [Documentation](https://vitest.dev/api/expect)
+180 -56
View File
@@ -1,6 +1,4 @@
import { Test } from '@vitest/runner';
import { MockInstance } from '@vitest/spy';
import { Constructable } from '@vitest/utils';
import { Formatter } from 'tinyrainbow';
import { StandardSchemaV1 } from '@standard-schema/spec';
import { diff, printDiffOrStringify } from '@vitest/utils/diff';
@@ -9,11 +7,6 @@ import { stringify } from '@vitest/utils/display';
import * as chai from 'chai';
export { chai };
declare const MATCHERS_OBJECT: unique symbol;
declare const JEST_MATCHERS_OBJECT: unique symbol;
declare const GLOBAL_EXPECT: unique symbol;
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
interface AsymmetricMatcherInterface {
asymmetricMatch: (other: unknown, customTesters?: Array<Tester>) => boolean;
toString: () => string;
@@ -131,9 +124,18 @@ interface MatcherState {
customTesters: Array<Tester>;
assertionCalls: number;
currentTestName?: string;
/**
* @deprecated exists only in types
*/
dontThrow?: () => void;
/**
* @deprecated exists only in types
*/
error?: Error;
equals: (a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean) => boolean;
/**
* @deprecated exists only in types
*/
expand?: boolean;
expectedAssertionsNumber?: number | null;
expectedAssertionsNumberErrorGen?: (() => Error) | null;
@@ -141,6 +143,9 @@ interface MatcherState {
isExpectingAssertionsError?: Error | null;
isNot: boolean;
promise: string;
/**
* @deprecated exists only in types
*/
suppressedErrors: Array<Error>;
testPath?: string;
utils: ReturnType<typeof getMatcherUtils> & {
@@ -151,13 +156,19 @@ interface MatcherState {
};
soft?: boolean;
poll?: boolean;
task?: Readonly<Test>;
/**
* The same assertion instance that chai plugins receive.
* @experimental
* @see {@link https://www.chaijs.com/guide/plugins/} Core Plugin Concepts
*/
readonly assertion: Assertion;
}
interface SyncExpectationResult {
pass: boolean;
message: () => string;
actual?: any;
expected?: any;
meta?: object;
}
type AsyncExpectationResult = Promise<SyncExpectationResult>;
type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
@@ -234,8 +245,6 @@ interface AsymmetricMatchersContaining extends CustomMatcher {
/**
* Matches if the received number is within a certain precision of the expected number.
*
* @param precision - Optional decimal precision for comparison. Default is 2.
*
* @example
* expect(10.45).toEqual(expect.closeTo(10.5, 1));
* expect(5.11).toEqual(expect.closeTo(5.12)); // with default precision
@@ -452,6 +461,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalledTimes(2);
* @deprecated Use `toHaveBeenCalledTimes` instead
*/
toBeCalledTimes: (times: number) => void;
/**
@@ -470,6 +480,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalled();
* @deprecated Use `toHaveBeenCalled` instead
*/
toBeCalled: () => void;
/**
@@ -488,6 +499,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toBeCalledWith('arg1', 42);
* @deprecated Use `toHaveBeenCalledWith` instead
*/
toBeCalledWith: <E extends any[]>(...args: E) => void;
/**
@@ -500,15 +512,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveBeenNthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
/**
* Ensure that a mock function is called with specific arguments on an Nth call.
*
* Alias for `expect.toHaveBeenNthCalledWith`.
*
* @example
* expect(mockFunc).nthCalledWith(2, 'secondArg');
*/
nthCalledWith: <E extends any[]>(nthCall: number, ...args: E) => void;
/**
* If you have a mock function, you can use `.toHaveBeenLastCalledWith`
* to test what arguments it was last called with.
*
@@ -519,16 +522,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveBeenLastCalledWith: <E extends any[]>(...args: E) => void;
/**
* If you have a mock function, you can use `.lastCalledWith`
* to test what arguments it was last called with.
*
* Alias for `expect.toHaveBeenLastCalledWith`.
*
* @example
* expect(mockFunc).lastCalledWith('lastArg');
*/
lastCalledWith: <E extends any[]>(...args: E) => void;
/**
* Used to test that a function throws when it is called.
*
* Also under the alias `expect.toThrowError`.
@@ -536,8 +529,9 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* @example
* expect(() => functionWithError()).toThrow('Error message');
* expect(() => parseJSON('invalid')).toThrow(SyntaxError);
* expect(() => { throw 42 }).toThrow(42);
*/
toThrow: (expected?: string | Constructable | RegExp | Error) => void;
toThrow: (expected?: any) => void;
/**
* Used to test that a function throws when it is called.
*
@@ -546,8 +540,10 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* @example
* expect(() => functionWithError()).toThrowError('Error message');
* expect(() => parseJSON('invalid')).toThrowError(SyntaxError);
* expect(() => { throw 42 }).toThrowError(42);
* @deprecated Use `toThrow` instead
*/
toThrowError: (expected?: string | Constructable | RegExp | Error) => void;
toThrowError: (expected?: any) => void;
/**
* Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
*
@@ -555,6 +551,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturn();
* @deprecated Use `toHaveReturned` instead
*/
toReturn: () => void;
/**
@@ -574,6 +571,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturnTimes(3);
* @deprecated Use `toHaveReturnedTimes` instead
*/
toReturnTimes: (times: number) => void;
/**
@@ -593,6 +591,7 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*
* @example
* expect(mockFunc).toReturnWith('returnValue');
* @deprecated Use `toHaveReturnedWith` instead
*/
toReturnWith: <E>(value: E) => void;
/**
@@ -616,17 +615,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
*/
toHaveLastReturnedWith: <E>(value: E) => void;
/**
* Use to test the specific value that a mock function last returned.
* If the last call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Alias for `expect.toHaveLastReturnedWith`.
*
* @example
* expect(mockFunc).lastReturnedWith('lastValue');
*/
lastReturnedWith: <E>(value: E) => void;
/**
* Use to test the specific value that a mock function returned for the nth call.
* If the nth call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
@@ -637,17 +625,6 @@ interface JestAssertion<T = any> extends jest.Matchers<void, T>, CustomMatcher {
* expect(mockFunc).toHaveNthReturnedWith(2, 'nthValue');
*/
toHaveNthReturnedWith: <E>(nthCall: number, value: E) => void;
/**
* Use to test the specific value that a mock function returned for the nth call.
* If the nth call to the mock function threw an error, then this matcher will fail
* no matter what value you provided as the expected return value.
*
* Alias for `expect.toHaveNthReturnedWith`.
*
* @example
* expect(mockFunc).nthReturnedWith(2, 'nthValue');
*/
nthReturnedWith: <E>(nthCall: number, value: E) => void;
}
type VitestAssertion<
A,
@@ -655,7 +632,7 @@ type VitestAssertion<
> = { [K in keyof A] : A[K] extends Chai.Assertion ? Assertion<T> : A[K] extends (...args: any[]) => any ? A[K] : VitestAssertion<A[K], T> } & ((type: string, message?: string) => Assertion);
type Promisify<O> = { [K in keyof O] : O[K] extends (...args: infer A) => infer R ? Promisify<O[K]> & ((...args: A) => Promise<R>) : O[K] };
type PromisifyAssertion<T> = Promisify<Assertion<T>>;
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, Matchers<T> {
interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAssertion<T>, ChaiMockAssertion, Matchers<T> {
/**
* Ensures a value is of a specific type.
*
@@ -759,6 +736,140 @@ interface Assertion<T = any> extends VitestAssertion<Chai.Assertion, T>, JestAss
*/
rejects: PromisifyAssertion<T>;
}
/**
* Chai-style assertions for spy/mock testing.
* These provide sinon-chai compatible assertion names that delegate to Jest-style implementations.
*/
interface ChaiMockAssertion {
/**
* Checks that a spy was called at least once.
* Chai-style equivalent of `toHaveBeenCalled`.
*
* @example
* expect(spy).to.have.been.called
*/
readonly called: Assertion;
/**
* Checks that a spy was called a specific number of times.
* Chai-style equivalent of `toHaveBeenCalledTimes`.
*
* @example
* expect(spy).to.have.callCount(3)
*/
callCount: (count: number) => void;
/**
* Checks that a spy was called with specific arguments at least once.
* Chai-style equivalent of `toHaveBeenCalledWith`.
*
* @example
* expect(spy).to.have.been.calledWith('arg1', 'arg2')
*/
calledWith: <E extends any[]>(...args: E) => void;
/**
* Checks that a spy was called exactly once.
* Chai-style equivalent of `toHaveBeenCalledOnce`.
*
* @example
* expect(spy).to.have.been.calledOnce
*/
readonly calledOnce: Assertion;
/**
* Checks that a spy was called exactly once with specific arguments.
* Chai-style equivalent of `toHaveBeenCalledExactlyOnceWith`.
*
* @example
* expect(spy).to.have.been.calledOnceWith('arg1', 'arg2')
*/
calledOnceWith: <E extends any[]>(...args: E) => void;
/**
* Checks that the last call to a spy was made with specific arguments.
* Chai-style equivalent of `toHaveBeenLastCalledWith`.
*
* @example
* expect(spy).to.have.been.lastCalledWith('arg1', 'arg2')
*/
lastCalledWith: <E extends any[]>(...args: E) => void;
/**
* Checks that the nth call to a spy was made with specific arguments.
* Chai-style equivalent of `toHaveBeenNthCalledWith`.
*
* @example
* expect(spy).to.have.been.nthCalledWith(2, 'arg1', 'arg2')
*/
nthCalledWith: <E extends any[]>(n: number, ...args: E) => void;
/**
* Checks that a spy returned a specific value at least once.
* Chai-style equivalent of `toHaveReturnedWith`.
*
* @example
* expect(spy).to.have.returned('value')
*/
returned: <E>(value: E) => void;
/**
* Checks that a spy returned a specific value at least once.
* Chai-style equivalent of `toHaveReturnedWith`.
*
* @example
* expect(spy).to.have.returnedWith('value')
*/
returnedWith: <E>(value: E) => void;
/**
* Checks that a spy returned successfully a specific number of times.
* Chai-style equivalent of `toHaveReturnedTimes`.
*
* @example
* expect(spy).to.have.returnedTimes(3)
*/
returnedTimes: (count: number) => void;
/**
* Checks that the last return value of a spy matches the expected value.
* Chai-style equivalent of `toHaveLastReturnedWith`.
*
* @example
* expect(spy).to.have.lastReturnedWith('value')
*/
lastReturnedWith: <E>(value: E) => void;
/**
* Checks that the nth return value of a spy matches the expected value.
* Chai-style equivalent of `toHaveNthReturnedWith`.
*
* @example
* expect(spy).to.have.nthReturnedWith(2, 'value')
*/
nthReturnedWith: <E>(n: number, value: E) => void;
/**
* Checks that a spy was called before another spy.
* Chai-style equivalent of `toHaveBeenCalledBefore`.
*
* @example
* expect(spy1).to.have.been.calledBefore(spy2)
*/
calledBefore: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
/**
* Checks that a spy was called after another spy.
* Chai-style equivalent of `toHaveBeenCalledAfter`.
*
* @example
* expect(spy1).to.have.been.calledAfter(spy2)
*/
calledAfter: (mock: MockInstance, failIfNoFirstInvocation?: boolean) => void;
/**
* Checks that a spy was called exactly twice.
* Chai-style equivalent of `toHaveBeenCalledTimes(2)`.
*
* @example
* expect(spy).to.have.been.calledTwice
*/
readonly calledTwice: Assertion;
/**
* Checks that a spy was called exactly three times.
* Chai-style equivalent of `toHaveBeenCalledTimes(3)`.
*
* @example
* expect(spy).to.have.been.calledThrice
*/
readonly calledThrice: Assertion;
}
declare global {
namespace jest {
interface Matchers<
@@ -768,6 +879,13 @@ declare global {
}
}
declare const ChaiStyleAssertions: ChaiPlugin;
declare const MATCHERS_OBJECT: unique symbol;
declare const JEST_MATCHERS_OBJECT: unique symbol;
declare const GLOBAL_EXPECT: unique symbol;
declare const ASYMMETRIC_MATCHERS_OBJECT: unique symbol;
declare const customMatchers: MatchersObject;
declare const JestChaiExpect: ChaiPlugin;
@@ -777,6 +895,7 @@ declare const JestExtend: ChaiPlugin;
declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean;
declare function isAsymmetric(obj: any): obj is AsymmetricMatcher<any>;
declare function hasAsymmetric(obj: any, seen?: Set<any>): boolean;
declare function isError(value: unknown): value is Error;
declare function isA(typeName: string, value: unknown): boolean;
declare function fnNameFor(func: Function): string;
declare function hasProperty(obj: object | null, property: string): boolean;
@@ -802,5 +921,10 @@ declare function isStandardSchema(obj: any): obj is StandardSchemaV1;
declare function getState<State extends MatcherState = MatcherState>(expect: ExpectStatic): State;
declare function setState<State extends MatcherState = MatcherState>(state: Partial<State>, expect: ExpectStatic): void;
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };
export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext };
declare function createAssertionMessage(util: Chai.ChaiUtils, assertion: Chai.Assertion, hasArgs: boolean): string;
declare function recordAsyncExpect(_test: any, promise: Promise<any>, assertion: string, error: Error, isSoft?: boolean): Promise<any>;
/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */
declare function wrapAssertion(utils: Chai.ChaiUtils, name: string, fn: (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike<void>): (this: Chai.AssertionStatic & Assertion, ...args: any[]) => void | PromiseLike<void>;
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion };
export type { Assertion, AsymmetricMatcherInterface, AsymmetricMatchersContaining, AsyncExpectationResult, ChaiMockAssertion, ChaiPlugin, DeeplyAllowMatchers, ExpectStatic, ExpectationResult, JestAssertion, MatcherHintOptions, MatcherState, Matchers, MatchersObject, PromisifyAssertion, RawMatcherFn, SyncExpectationResult, Tester, TesterContext };
+157 -80
View File
@@ -1,6 +1,6 @@
import { printDiffOrStringify, diff } from '@vitest/utils/diff';
import { stringify } from '@vitest/utils/display';
import { getType, isObject, noop, assertTypes } from '@vitest/utils/helpers';
import { getType, isObject, noop, assertTypes, ordinal } from '@vitest/utils/helpers';
import c from 'tinyrainbow';
import { isMockFunction } from '@vitest/spy';
import { processError } from '@vitest/utils/error';
@@ -8,6 +8,56 @@ import { use, util } from 'chai';
import * as chai from 'chai';
export { chai };
const ChaiStyleAssertions = (chai, utils) => {
function defProperty(name, delegateTo) {
utils.addProperty(chai.Assertion.prototype, name, function() {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this);
});
}
function defPropertyWithArgs(name, delegateTo, ...args) {
utils.addProperty(chai.Assertion.prototype, name, function() {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this, ...args);
});
}
function defMethod(name, delegateTo) {
utils.addMethod(chai.Assertion.prototype, name, function(...args) {
const jestMethod = chai.Assertion.prototype[delegateTo];
if (!jestMethod) {
throw new Error(`Cannot delegate to ${String(delegateTo)}: method not found. Ensure JestChaiExpect plugin is loaded first.`);
}
return jestMethod.call(this, ...args);
});
}
// API to (somewhat) mirror sinon-chai
// https://github.com/chaijs/sinon-chai
defProperty("called", "toHaveBeenCalled");
defProperty("calledOnce", "toHaveBeenCalledOnce");
defPropertyWithArgs("calledTwice", "toHaveBeenCalledTimes", 2);
defPropertyWithArgs("calledThrice", "toHaveBeenCalledTimes", 3);
defMethod("callCount", "toHaveBeenCalledTimes");
defMethod("calledWith", "toHaveBeenCalledWith");
defMethod("calledOnceWith", "toHaveBeenCalledExactlyOnceWith");
defMethod("lastCalledWith", "toHaveBeenLastCalledWith");
defMethod("nthCalledWith", "toHaveBeenNthCalledWith");
defMethod("returned", "toHaveReturned");
defMethod("returnedWith", "toHaveReturnedWith");
defMethod("returnedTimes", "toHaveReturnedTimes");
defMethod("lastReturnedWith", "toHaveLastReturnedWith");
defMethod("nthReturnedWith", "toHaveNthReturnedWith");
defMethod("calledBefore", "toHaveBeenCalledBefore");
defMethod("calledAfter", "toHaveBeenCalledAfter");
// TODO: implement
// defMethod('thrown', 'toHaveThrown')
};
const MATCHERS_OBJECT = Symbol.for("matchers-object");
const JEST_MATCHERS_OBJECT = Symbol.for("$$jest-matchers-object");
const GLOBAL_EXPECT = Symbol.for("expect-global");
@@ -198,6 +248,18 @@ function asymmetricMatch(a, b, customTesters) {
return b.asymmetricMatch(a, customTesters);
}
}
// https://github.com/jestjs/jest/blob/905bcbced3d40cdf7aadc4cdf6fb731c4bb3dbe3/packages/expect-utils/src/utils.ts#L509
function isError(value) {
if (typeof Error.isError === "function") {
return Error.isError(value);
}
switch (Object.prototype.toString.call(value)) {
case "[object Error]":
case "[object Exception]":
case "[object DOMException]": return true;
default: return value instanceof Error;
}
}
// Equality function lovingly adapted from isEqual in
// [Underscore](http://underscorejs.org)
function eq(a, b, aStack, bStack, customTesters, hasKey) {
@@ -286,7 +348,7 @@ function eq(a, b, aStack, bStack, customTesters, hasKey) {
if (className === "[object Array]" && a.length !== b.length) {
return false;
}
if (a instanceof Error && b instanceof Error) {
if (isError(a) && isError(b)) {
try {
return isErrorEqual(a, b, aStack, bStack, customTesters, hasKey);
} finally {
@@ -320,17 +382,17 @@ function isErrorEqual(a, b, aStack, bStack, customTesters, hasKey) {
// - [[Prototype]] of objects are compared using the === operator.
// - Only enumerable "own" properties are considered.
// - Error names, messages, causes, and errors are always compared, even if these are not enumerable properties. errors is also compared.
let result = Object.getPrototypeOf(a) === Object.getPrototypeOf(b) && a.name === b.name && a.message === b.message;
let result = Object.prototype.toString.call(a) === Object.prototype.toString.call(b) && a.name === b.name && a.message === b.message;
// check Error.cause asymmetrically
if (typeof b.cause !== "undefined") {
result && (result = eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey));
result &&= eq(a.cause, b.cause, aStack, bStack, customTesters, hasKey);
}
// AggregateError.errors
if (a instanceof AggregateError && b instanceof AggregateError) {
result && (result = eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey));
result &&= eq(a.errors, b.errors, aStack, bStack, customTesters, hasKey);
}
// spread to compare enumerable properties
result && (result = eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey));
result &&= eq({ ...a }, { ...b }, aStack, bStack, customTesters, hasKey);
return result;
}
function keys(obj, hasKey) {
@@ -524,7 +586,7 @@ function hasPropertyInObject(object, key) {
return Object.hasOwn(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key);
}
function isObjectWithKeys(a) {
return isObject(a) && !(a instanceof Error) && !Array.isArray(a) && !(a instanceof Date);
return isObject(a) && !isError(a) && !Array.isArray(a) && !(a instanceof Date) && !(a instanceof Set) && !(a instanceof Map);
}
function subsetEquality(object, subset, customTesters = []) {
const filteredCustomTesters = customTesters.filter((t) => t !== subsetEquality);
@@ -607,10 +669,7 @@ function pluralize(word, count) {
return `${count} ${word}${count === 1 ? "" : "s"}`;
}
function getObjectKeys(object) {
return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => {
var _Object$getOwnPropert;
return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(object, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable;
})];
return [...Object.keys(object), ...Object.getOwnPropertySymbols(object).filter((s) => Object.getOwnPropertyDescriptor(object, s)?.enumerable)];
}
function getObjectSubset(object, subset, customTesters) {
let stripped = 0;
@@ -788,10 +847,7 @@ class ObjectContaining extends AsymmetricMatcher {
return this.hasProperty(this.getPrototype(obj), property);
}
getProperties(obj) {
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => {
var _Object$getOwnPropert;
return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(obj, s)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.enumerable;
})];
return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj).filter((s) => Object.getOwnPropertyDescriptor(obj, s)?.enumerable)];
}
asymmetricMatch(other, customTesters) {
if (typeof this.sample !== "object") {
@@ -800,13 +856,12 @@ class ObjectContaining extends AsymmetricMatcher {
let result = true;
const properties = this.getProperties(this.sample);
for (const property of properties) {
var _Object$getOwnPropert2, _Object$getOwnPropert3;
if (!this.hasProperty(other, property)) {
result = false;
break;
}
const value = ((_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(this.sample, property)) === null || _Object$getOwnPropert2 === void 0 ? void 0 : _Object$getOwnPropert2.value) ?? this.sample[property];
const otherValue = ((_Object$getOwnPropert3 = Object.getOwnPropertyDescriptor(other, property)) === null || _Object$getOwnPropert3 === void 0 ? void 0 : _Object$getOwnPropert3.value) ?? other[property];
const value = this.sample[property];
const otherValue = other[property];
if (!equals(value, otherValue, customTesters)) {
result = false;
break;
@@ -987,9 +1042,8 @@ class SchemaMatching extends AsymmetricMatcher {
return "object";
}
toAsymmetricMatcher() {
var _this$result;
const { utils } = this.getMatcherContext();
const issues = ((_this$result = this.result) === null || _this$result === void 0 ? void 0 : _this$result.issues) || [];
const issues = this.result?.issues || [];
if (issues.length > 0) {
return `${this.toString()} ${utils.stringify(this.result, undefined, { printBasicPrototype: false })}`;
}
@@ -1017,13 +1071,14 @@ const JestAsymmetricMatchers = (chai, utils) => {
};
function createAssertionMessage(util, assertion, hasArgs) {
const soft = util.flag(assertion, "soft") ? ".soft" : "";
const not = util.flag(assertion, "negate") ? "not." : "";
const name = `${util.flag(assertion, "_name")}(${hasArgs ? "expected" : ""})`;
const promiseName = util.flag(assertion, "promise");
const promise = promiseName ? `.${promiseName}` : "";
return `expect(actual)${promise}.${not}${name}`;
return `expect${soft}(actual)${promise}.${not}${name}`;
}
function recordAsyncExpect(_test, promise, assertion, error) {
function recordAsyncExpect(_test, promise, assertion, error, isSoft) {
const test = _test;
// record promise for test, that resolves before test ends
if (test && promise instanceof Promise) {
@@ -1041,17 +1096,23 @@ function recordAsyncExpect(_test, promise, assertion, error) {
if (!test.promises) {
test.promises = [];
}
// setup `expect.soft` handler here instead of `wrapAssertion`
// to avoid double error tracking while keeping non-await promise detection.
if (isSoft) {
promise = promise.then(noop, (err) => {
handleTestError(test, err);
});
}
test.promises.push(promise);
let resolved = false;
test.onFinished ?? (test.onFinished = []);
test.onFinished ??= [];
test.onFinished.push(() => {
if (!resolved) {
var _vitest_worker__;
const processor = ((_vitest_worker__ = globalThis.__vitest_worker__) === null || _vitest_worker__ === void 0 ? void 0 : _vitest_worker__.onFilterStackTrace) || ((s) => s || "");
const processor = globalThis.__vitest_worker__?.onFilterStackTrace || ((s) => s || "");
const stack = processor(error.stack);
console.warn([
`Promise returned by \`${assertion}\` was not awaited. `,
"Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in Vitest 3. ",
"Vitest currently auto-awaits hanging assertions at the end of the test, but this will cause the test to fail in the next Vitest major. ",
"Please remember to await the assertion.\n",
stack
].join(""));
@@ -1063,9 +1124,11 @@ function recordAsyncExpect(_test, promise, assertion, error) {
return promise.then(onFulfilled, onRejected);
},
catch(onRejected) {
resolved = true;
return promise.catch(onRejected);
},
finally(onFinally) {
resolved = true;
return promise.finally(onFinally);
},
[Symbol.toStringTag]: "Promise"
@@ -1074,12 +1137,12 @@ function recordAsyncExpect(_test, promise, assertion, error) {
return promise;
}
function handleTestError(test, err) {
var _test$result;
test.result || (test.result = { state: "fail" });
test.result ||= { state: "fail" };
test.result.state = "fail";
(_test$result = test.result).errors || (_test$result.errors = []);
test.result.errors ||= [];
test.result.errors.push(processError(err));
}
/** wrap assertion function to support `expect.soft` and provide assertion name as `_name` */
function wrapAssertion(utils, name, fn) {
return function(...args) {
// private
@@ -1087,7 +1150,11 @@ function wrapAssertion(utils, name, fn) {
utils.flag(this, "_name", name);
}
if (!utils.flag(this, "soft")) {
return fn.apply(this, args);
// avoid WebKit's proper tail call to preserve stacktrace offset for inline snapshot
// https://webkit.org/blog/6240/ecmascript-6-proper-tail-calls-in-webkit
try {
return fn.apply(this, args);
} finally {}
}
const test = utils.flag(this, "vitest-test");
if (!test) {
@@ -1437,15 +1504,15 @@ const JestChaiExpect = (chai, utils) => {
throw new AssertionError(formatCalls(spy, msg, args));
}
});
def(["toHaveBeenNthCalledWith", "nthCalledWith"], function(times, ...args) {
def("toHaveBeenNthCalledWith", function(times, ...args) {
const spy = getSpy(this);
const spyName = spy.getMockName();
const nthCall = spy.mock.calls[times - 1];
const callCount = spy.mock.calls.length;
const isCalled = times <= callCount;
this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinalOf(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinalOf(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled);
this.assert(nthCall && equalsArgumentArray(nthCall, args), `expected ${ordinal(times)} "${spyName}" call to have been called with #{exp}${isCalled ? `` : `, but called only ${callCount} times`}`, `expected ${ordinal(times)} "${spyName}" call to not have been called with #{exp}`, args, nthCall, isCalled);
});
def(["toHaveBeenLastCalledWith", "lastCalledWith"], function(...args) {
def("toHaveBeenLastCalledWith", function(...args) {
const spy = getSpy(this);
const spyName = spy.getMockName();
const lastCall = spy.mock.calls.at(-1);
@@ -1516,7 +1583,7 @@ const JestChaiExpect = (chai, utils) => {
const name = expected.name || expected.prototype.constructor.name;
return this.assert(thrown && thrown instanceof expected, `expected error to be instance of ${name}`, `expected error not to be instance of ${name}`, expected, thrown);
}
if (expected instanceof Error) {
if (isError(expected)) {
const equal = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected a thrown error to be #{exp}", "expected a thrown error not to be #{exp}", expected, thrown);
}
@@ -1524,7 +1591,8 @@ const JestChaiExpect = (chai, utils) => {
const matcher = expected;
return this.assert(thrown && matcher.asymmetricMatch(thrown), "expected error to match asymmetric matcher", "expected error not to match asymmetric matcher", matcher, thrown);
}
throw new Error(`"toThrow" expects string, RegExp, function, Error instance or asymmetric matcher, got "${typeof expected}"`);
const equal = equals(thrown, expected, [...customTesters, iterableEquality]);
return this.assert(equal, "expected a thrown value to equal #{exp}", "expected a thrown value not to equal #{exp}", expected, thrown);
});
[{
name: "toHaveResolved",
@@ -1592,7 +1660,7 @@ const JestChaiExpect = (chai, utils) => {
},
action: "resolve"
}, {
name: ["toHaveLastReturnedWith", "lastReturnedWith"],
name: "toHaveLastReturnedWith",
condition: (spy, value) => {
const result = spy.mock.results.at(-1);
return Boolean(result && result.type === "return" && equals(result.value, value));
@@ -1604,7 +1672,7 @@ const JestChaiExpect = (chai, utils) => {
const results = action === "return" ? spy.mock.results : spy.mock.settledResults;
const result = results.at(-1);
const spyName = spy.getMockName();
this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value);
this.assert(condition(spy, value), `expected last "${spyName}" call to ${action} #{exp}`, `expected last "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
});
[{
@@ -1615,7 +1683,7 @@ const JestChaiExpect = (chai, utils) => {
},
action: "resolve"
}, {
name: ["toHaveNthReturnedWith", "nthReturnedWith"],
name: "toHaveNthReturnedWith",
condition: (spy, index, value) => {
const result = spy.mock.results[index - 1];
return result && result.type === "return" && equals(result.value, value);
@@ -1627,8 +1695,8 @@ const JestChaiExpect = (chai, utils) => {
const spyName = spy.getMockName();
const results = action === "return" ? spy.mock.results : spy.mock.settledResults;
const result = results[nthCall - 1];
const ordinalCall = `${ordinalOf(nthCall)} call`;
this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result === null || result === void 0 ? void 0 : result.value);
const ordinalCall = `${ordinal(nthCall)} call`;
this.assert(condition(spy, nthCall, value), `expected ${ordinalCall} "${spyName}" call to ${action} #{exp}`, `expected ${ordinalCall} "${spyName}" call to not ${action} #{exp}`, value, result?.value);
});
});
// @ts-expect-error @internal
@@ -1647,7 +1715,7 @@ const JestChaiExpect = (chai, utils) => {
if (utils.flag(this, "poll")) {
throw new SyntaxError(`expect.poll() is not supported in combination with .resolves`);
}
if (typeof (obj === null || obj === void 0 ? void 0 : obj.then) !== "function") {
if (typeof obj?.then !== "function") {
throw new TypeError(`You must provide a Promise to expect() when using .resolves, not '${typeof obj}'.`);
}
const proxy = new Proxy(this, { get: (target, key, receiver) => {
@@ -1657,16 +1725,20 @@ const JestChaiExpect = (chai, utils) => {
}
return (...args) => {
utils.flag(this, "_name", key);
const promise = obj.then((value) => {
const promise = Promise.resolve(obj).then((value) => {
utils.flag(this, "object", value);
return result.call(this, ...args);
}, (err) => {
const _error = new AssertionError(`promise rejected "${utils.inspect(err)}" instead of resolving`, { showDiff: false });
_error.cause = err;
_error.stack = error.stack.replace(error.message, _error.message);
throw _error;
}).catch((err) => {
if (isError(err) && error.stack) {
err.stack = error.stack.replace(error.message, err.message);
}
throw err;
});
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error);
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
@@ -1681,7 +1753,7 @@ const JestChaiExpect = (chai, utils) => {
if (utils.flag(this, "poll")) {
throw new SyntaxError(`expect.poll() is not supported in combination with .rejects`);
}
if (typeof (wrapper === null || wrapper === void 0 ? void 0 : wrapper.then) !== "function") {
if (typeof wrapper?.then !== "function") {
throw new TypeError(`You must provide a Promise to expect() when using .rejects, not '${typeof wrapper}'.`);
}
const proxy = new Proxy(this, { get: (target, key, receiver) => {
@@ -1691,42 +1763,32 @@ const JestChaiExpect = (chai, utils) => {
}
return (...args) => {
utils.flag(this, "_name", key);
const promise = wrapper.then((value) => {
const promise = Promise.resolve(wrapper).then((value) => {
const _error = new AssertionError(`promise resolved "${utils.inspect(value)}" instead of rejecting`, {
showDiff: true,
expected: new Error("rejected promise"),
actual: value
});
_error.stack = error.stack.replace(error.message, _error.message);
throw _error;
}, (err) => {
utils.flag(this, "object", err);
return result.call(this, ...args);
}).catch((err) => {
if (isError(err) && error.stack) {
err.stack = error.stack.replace(error.message, err.message);
}
throw err;
});
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error);
return recordAsyncExpect(test, promise, createAssertionMessage(utils, this, !!args.length), error, utils.flag(this, "soft"));
};
} });
return proxy;
});
};
function ordinalOf(i) {
const j = i % 10;
const k = i % 100;
if (j === 1 && k !== 11) {
return `${i}st`;
}
if (j === 2 && k !== 12) {
return `${i}nd`;
}
if (j === 3 && k !== 13) {
return `${i}rd`;
}
return `${i}th`;
}
function formatCalls(spy, msg, showActualCall) {
if (spy.mock.calls.length) {
msg += c.gray(`\n\nReceived: \n\n${spy.mock.calls.map((callArg, i) => {
let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call:\n\n`);
msg += c.gray(`\n\nReceived:\n\n${spy.mock.calls.map((callArg, i) => {
let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call:\n\n`);
if (showActualCall) {
methodCall += diff(showActualCall, callArg, { omitAnnotationLines: true });
} else {
@@ -1741,8 +1803,8 @@ function formatCalls(spy, msg, showActualCall) {
}
function formatReturns(spy, results, msg, showActualReturn) {
if (results.length) {
msg += c.gray(`\n\nReceived: \n\n${results.map((callReturn, i) => {
let methodCall = c.bold(` ${ordinalOf(i + 1)} ${spy.getMockName()} call return:\n\n`);
msg += c.gray(`\n\nReceived:\n\n${results.map((callReturn, i) => {
let methodCall = c.bold(` ${ordinal(i + 1)} ${spy.getMockName()} call return:\n\n`);
if (showActualReturn) {
methodCall += diff(showActualReturn, callReturn.value, { omitAnnotationLines: true });
} else {
@@ -1769,13 +1831,12 @@ function getMatcherState(assertion, expect) {
subsetEquality
};
let task = util.flag(assertion, "vitest-test");
const currentTestName = (task === null || task === void 0 ? void 0 : task.fullTestName) ?? "";
if ((task === null || task === void 0 ? void 0 : task.type) !== "test") {
const currentTestName = task?.fullTestName ?? "";
if (task?.type !== "test") {
task = undefined;
}
const matcherState = {
...getState(expect),
task,
currentTestName,
customTesters: getCustomEqualityTesters(),
isNot,
@@ -1784,8 +1845,10 @@ function getMatcherState(assertion, expect) {
equals,
suppressedErrors: [],
soft: util.flag(assertion, "soft"),
poll: util.flag(assertion, "poll")
poll: util.flag(assertion, "poll"),
assertion
};
Object.assign(matcherState, { task });
return {
state: matcherState,
isNot,
@@ -1794,36 +1857,50 @@ function getMatcherState(assertion, expect) {
};
}
class JestExtendError extends Error {
constructor(message, actual, expected) {
constructor(message, actual, expected, __vitest_error_context__) {
super(message);
this.actual = actual;
this.expected = expected;
this.__vitest_error_context__ = __vitest_error_context__;
}
}
function JestExtendPlugin(c, expect, matchers) {
return (_, utils) => {
Object.entries(matchers).forEach(([expectAssertionName, expectAssertion]) => {
function expectWrapper(...args) {
function __VITEST_EXTEND_ASSERTION__(...args) {
const { state, isNot, obj, customMessage } = getMatcherState(this, expect);
const result = expectAssertion.call(state, obj, ...args);
if (result && typeof result === "object" && typeof result.then === "function") {
const thenable = result;
return thenable.then(({ pass, message, actual, expected }) => {
return thenable.then(({ pass, message, actual, expected, meta }) => {
if (pass && isNot || !pass && !isNot) {
const errorMessage = customMessage != null ? customMessage : message();
throw new JestExtendError(errorMessage, actual, expected);
const errorMessage = (customMessage ? `${customMessage}: ` : "") + message();
throw new JestExtendError(errorMessage, actual, expected, {
assertionName: expectAssertionName,
meta
});
}
});
}
const { pass, message, actual, expected } = result;
const { pass, message, actual, expected, meta } = result;
if (pass && isNot || !pass && !isNot) {
const errorMessage = customMessage != null ? customMessage : message();
throw new JestExtendError(errorMessage, actual, expected);
const errorMessage = (customMessage ? `${customMessage}: ` : "") + message();
throw new JestExtendError(errorMessage, actual, expected, {
assertionName: expectAssertionName,
meta
});
}
}
const softWrapper = wrapAssertion(utils, expectAssertionName, expectWrapper);
const softWrapper = wrapAssertion(utils, expectAssertionName, __VITEST_EXTEND_ASSERTION__);
utils.addMethod(globalThis[JEST_MATCHERS_OBJECT].matchers, expectAssertionName, softWrapper);
utils.addMethod(c.Assertion.prototype, expectAssertionName, softWrapper);
// `expect.poll()` inspects the installed Chai assertion method,
// so copy the internal marker from the original matcher function.
// this is only for domain snapshot matchers for now.
if (expectAssertion.__vitest_poll_takeover__) {
const addedMethod = c.Assertion.prototype[expectAssertionName];
Object.defineProperty(addedMethod, "__vitest_poll_takeover__", { value: true });
}
class CustomMatcher extends AsymmetricMatcher {
constructor(inverse = false, ...sample) {
super(sample, inverse);
@@ -1872,4 +1949,4 @@ const JestExtend = (chai, utils) => {
});
};
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, setState, sparseArrayEquality, subsetEquality, typeEquality };
export { ASYMMETRIC_MATCHERS_OBJECT, Any, Anything, ArrayContaining, AsymmetricMatcher, ChaiStyleAssertions, GLOBAL_EXPECT, JEST_MATCHERS_OBJECT, JestAsymmetricMatchers, JestChaiExpect, JestExtend, MATCHERS_OBJECT, ObjectContaining, SchemaMatching, StringContaining, StringMatching, addCustomEqualityTesters, arrayBufferEquality, createAssertionMessage, customMatchers, equals, fnNameFor, generateToBeMessage, getObjectKeys, getObjectSubset, getState, hasAsymmetric, hasProperty, isA, isAsymmetric, isError, isImmutableUnorderedKeyed, isImmutableUnorderedSet, isStandardSchema, iterableEquality, pluralize, recordAsyncExpect, setState, sparseArrayEquality, subsetEquality, typeEquality, wrapAssertion };
+14 -8
View File
@@ -1,11 +1,11 @@
{
"name": "@vitest/expect",
"type": "module",
"version": "4.0.18",
"version": "4.1.9",
"description": "Jest's expect matchers as a Chai plugin",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
"homepage": "https://github.com/vitest-dev/vitest/tree/main/packages/expect#readme",
"homepage": "https://vitest.dev/api/expect",
"repository": {
"type": "git",
"url": "git+https://github.com/vitest-dev/vitest.git",
@@ -14,6 +14,12 @@
"bugs": {
"url": "https://github.com/vitest-dev/vitest/issues"
},
"keywords": [
"vitest",
"test",
"chai",
"assertion"
],
"sideEffects": false,
"exports": {
".": {
@@ -29,15 +35,15 @@
"dist"
],
"dependencies": {
"@standard-schema/spec": "^1.0.0",
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"chai": "^6.2.1",
"tinyrainbow": "^3.0.3",
"@vitest/spy": "4.0.18",
"@vitest/utils": "4.0.18"
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0",
"@vitest/spy": "4.1.9",
"@vitest/utils": "4.1.9"
},
"devDependencies": {
"@vitest/runner": "4.0.18"
"@vitest/runner": "4.1.9"
},
"scripts": {
"build": "premove dist && rollup -c",