Skip to content
On this page

API Reference

Validators

.toBeA<C extends NewableOrPrimitive>(type: C): void

Asserts that the value is an instance of a provided class or a primitive type. It is compatible with built-in types like strings, numbers, and dates.

If you want to match a nested value, use the matcher expect.a(type) instead.

Parameters:

  • type - The class or primitive constructor to match against.

Examples:

ts
// Primitives
expect(123).toBeA(Number)
expect('foo').not.toBeA(Boolean)

// Classes
expect(new Person('John', 'Doe')).toBeA(Person)

.toBeASafeInteger(this: Validators<number | bigint>): void

Asserts that a value is an integer or a bigint and falls within the safe range of values as defined by Number.MIN_SAFE_INTEGER and Number.MAX_SAFE_INTEGER.

If you want to match a nested value, use the matcher expect.safeInteger() instead.

Examples:

ts
expect(100).toBeASafeInteger()
expect(100n).toBeASafeInteger()

expect(100.5).not.toBeASafeInteger()
expect(Number.MAX_SAFE_INTEGER * 2).not.toBeASafeInteger()

.toBeAnInteger(this: Validators<number | bigint>): void

Asserts that a value is an integer or a bigint.

You can also check that the integer is within the safe range of values by using expect(...).toBeASafeInteger()

If you want to match a nested value, use the matcher expect.integer() instead.

Examples:

ts
expect(100).toBeAnInteger()
expect(100n).toBeAnInteger()

expect(100.5).not.toBeAnInteger()

.toBeBetween(this: Validators<number | bigint>, min: number | bigint, max: number | bigint): void

Asserts that a number is between the two numbers. The range is [min, max], inclusive on both sides.

Works for both numbers and bigints.

If you want to match a nested value, use the matcher expect.toBeBetween(min, max) instead.

Parameters:

  • min - The minimum value, inclusive.
  • max - The maximum value, inclusive.

Examples:

ts
expect(0.5).toBeBetween(0, 1)
expect(100n).toBeBetween(-200n, 200n)

expect(20).not.toBeBetween(0, 1)

.toBeCloseTo(this: Validators<number>, target: number, delta: number): void

Asserts that a number is close to the target value.The range is [target - delta, target + delta], inclusive on both sides.

Works only for numbers and not for bigints.

If you want to match a nested value, use the matcher expect.toBeCloseTo(target, delta) instead.

Parameters:

  • target - The number to aim for.
  • delta - The maximum difference between the values.

Examples:

ts
expect(0.5).toBeBetween(0, 1)
expect(100n).toBeBetween(-200n, 200n)

expect(20).not.toBeBetween(0, 1)

.toBeEmpty(this: Validators<string | any[] | Set<any> | Map<any, any>>): void

Asserts that a string, array, sets or map is empty.

If you want to match a nested value, use the matcher expect.empty() instead.

Examples:

ts
expect([]).toBeEmpty()
expect(new Map()).toBeEmpty()

expect('foo').not.toBeEmpty()
expect(new Set([1, 2, 3])).not.toBeEmpty()

.toBeFalsy(): void

Asserts that a value is falsy, as defined by: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

You can also use its sister validator, toBeTruthy, to match the opposite.

If you want to match a nested value, use the matcher expect.falsy() instead.

Examples:

ts
expect(0).toBeFalsy()
expect('').toBeFalsy()
expect(false).toBeFalsy()
expect(null).toBeFalsy()

expect(1).not.toBeFalsy()
expect('foo').not.toBeFalsy()
expect(true).not.toBeFalsy()
expect({ x: 1, y: 2 }).not.toBeFalsy()

.toBeGreaterThan(this: Validators<number | bigint>, target: number | bigint): void

Asserts that a number is greater than the target value.

Works for both numbers and bigints.

If you want to match a nested value, use the matcher expect.greaterThan(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect(100_000n).toBeGreaterThan(50_000n)

expect(1337n).not.toBeGreaterThan(1337n)
expect(0xcafebabe).not.toBeGreaterThan(0xdeadbeef)

.toBeGreaterThanOrEqual(this: Validators<number | bigint>, target: number | bigint): void

Asserts that a number is greater than or equal to the target value.

Works for both numbers and bigints.

If you want to match a nested value, use the matcher expect.greaterThanOrEqual(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect(100_000n).toBeGreaterThanOrEqual(50_000n)
expect(1337n).toBeGreaterThanOrEqual(1337n)

expect(0xcafebabe).not.toBeGreaterThanOrEqual(0xdeadbeef)

.toBeLessThan(this: Validators<number | bigint>, target: number | bigint): void

Asserts that a number is less the target value.

Works for both numbers and bigints.

If you want to match a nested value, use the matcher expect.lessThan(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect(50_000n).toBeLessThan(100_000n)

expect(1337n).not.toBeLessThan(1337n)
expect(0xdeadbeef).not.toBeLessThan(0xcafebabe)

.toBeLessThanOrEqual(this: Validators<number | bigint>, target: number | bigint): void

Asserts that a number is less than or equal to the target value.

Works for both numbers and bigints.

If you want to match a nested value, use the matcher expect.lessThanOrEqual(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect(50_000n).toBeLessThanOrEqual(100_000n)
expect(1337n).toBeLessThanOrEqual(1337n)

expect(0xdeadbeef).not.toBeLessThanOrEqual(0xcafebabe)

.toBeNullish(): void

Asserts that a value is nullish, meaning it is either null or undefined.

If you want to match a nested value, use the matcher expect.nullish() or expect.notNullish() instead.

Examples:

ts
expect(null).toBeNullish()
expect(undefined).toBeNullish()

expect('foo').not.toBeNullish()
expect({ x: 1 }).not.toBeNullish()

.toBeRejected(this: Validators<(() => Promise<any>) | Promise<any>>): Promise<void>

Asserts that an async function or a promise was rejected.

The result of this validator is a promise, so you can need to use it with await.

To also assert the error message, use toBeRejectedWith.

Examples:

ts
await expect(async () => {
  throw new Error('foo')
}).toBeRejected()

await expect(Promise.reject(new Error('foo'))).toBeRejected()

.toBeRejectedWith(this: Validators<(() => Promise<any>) | Promise<any>>, errorClass: new (...args: any[]) => Error, message?: string | RegExp): Promise<void>

Asserts that an async function or a promise was rejected with a given message and/or error class.

The result of this validator is a promise, so you can need to use it with await.

Parameters:

  • errorClass - The error class to check.
  • message - A substring of the error message or a regex matching the message.

Examples:

ts
// checking the error message with a substring
await expect(async () => {
  throw new Error('no pancakes found')
}).toBeRejectedWith('pancakes')

// checking the error message with a regex
await expect(Promise.reject(new Error('12345'))).toBeRejectedWith(
  /^\d+$/,
)

// checking the error class
await expect(async () => {
  throw new TypeError('magic')
}).toBeRejectedWith(TypeError)

// checking the error class and message
await expect(async () => 1n / 0n).toBeRejectedWith(
  RangeError,
  'Division by zero',
)

.toBeRejectedWith(this: Validators<(() => Promise<any>) | Promise<any>>, message: string | RegExp): Promise<void>

Asserts that an async function or a promise was rejected with a given message and/or error class.

The result of this validator is a promise, so you can need to use it with await.

Parameters:

  • message - A substring of the error message or a regex matching the message.

Examples:

ts
// checking the error message with a substring
await expect(async () => {
  throw new Error('no pancakes found')
}).toBeRejectedWith('pancakes')

// checking the error message with a regex
await expect(Promise.reject(new Error('12345'))).toBeRejectedWith(
  /^\d+$/,
)

// checking the error class
await expect(async () => {
  throw new TypeError('magic')
}).toBeRejectedWith(TypeError)

// checking the error class and message
await expect(async () => 1n / 0n).toBeRejectedWith(
  RangeError,
  'Division by zero',
)

.toBeTruthy(): void

Asserts that a value is truthy, as defined by: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

You can also use its sister validator, toBeFalsy, to match the opposite.

If you want to match a nested value, use the matcher expect.truthy() instead.

Examples:

ts
expect(1).toBeTruthy()
expect('foo').toBeTruthy()
expect(true).toBeTruthy()
expect({ x: 1, y: 2 }).toBeTruthy()

expect(0).not.toBeTruthy()
expect('').not.toBeTruthy()
expect(false).not.toBeTruthy()
expect(null).not.toBeTruthy()

.toEqual(expected: T): void

Asserts that a value is equal to another value. The equality is checked using the isEqual function. This means that it checks objects recursively, accounts for object prototypes and uses same value zero algorithm for primitives.

This validator also supports asymmetric matchers on the expected value.

Because this validator also works on the type level you will receive editor suggestions for the properties on the expected value based on the actual value.

To opt out of type checking you can explicitly provide unknown as the type parameter.

ts
expect<unknown>(1).not.toEqual('foo')

If you would like instead to check values for referential equality use the toExactlyEqual validator instead.

Alternatively if you would like to ignore type level checks and object prototypes use the toLooseEqual validator instead.

Parameters:

  • expected - The expected value. Can include nested matchers.

Examples:

ts
expect(1).toEqual(1)
expect(2).not.toEqual(3)

expect({ foo: 'bar' }).toEqual({ foo: 'bar' })

expect({ x: 15, y: -20 }).toEqual({
  x: expect.greaterThan(0),
  y: expect.lessThan(0),
})

// type-error: the type string is not assignable to number
expect(123).not.toEqual('foo')

.toEqualUnsorted(this: Validators<any[]>, expected: T): void

Asserts that an array is equal to another array if the order of the items is to be disregarded.

This validator supports matchers, but extreme caution should be exercised when using them. The algorithm used to compare the arrays does not check all possible permutations, so it is possible that the matcher will match a value that was provided verbatim later in the expected array.

Using matchers with this validator is only recommended for advanced users that know what they are doing!

Parameters:

  • expected - The array of expected items.

Examples:

ts
expect([1, 2, 3]).toEqualUnsorted([3, 1, 2])

expect(['foo', 'bar']).not.toEqualUnsorted(['a', 'b', 'c'])

.toExactlyEqual(this: Validators<object>, expected: unknown): void

Asserts that a value is referentially equal to the expected value.

This validator shouldn't be used for primitives or deep equality checks. Use toEqual instead.

Parameters:

  • expected - The expected value.

Examples:

ts
const vector = { x: 5, y: 7 }
expect(vector).toExactlyEqual(vector)

expect(vector).not.toExactlyEqual({ x: 5, y: 7 })

.toHaveBeenCalled(this: Validators<MockFunction<any[], any>>): void

Asserts that the mock function has been called at least once.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn1 = mockFn().returns(42)
fn1()
expect(fn1).toHaveBeenCalled()

const fn2 = mockFn().returns(42)
expect(fn2).not.toHaveBeenCalled()

.toHaveBeenCalledTimes(this: Validators<MockFunction<any[], any>>, times: number): void

Asserts that the mock function was called the given number of times.

Parameters:

  • times - The number of times the mock function was expected to be called.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn = mockFn().returns(42)
fn()
expect(fn).toHaveBeenCalledTimes(1)
expect(fn).not.toHaveBeenCalledTimes(2)

.toHaveBeenCalledWith(this: Validators<MockFunction<any[], any>>, ...args: MockParameters<T>): void

Asserts that the mock function was called at least once with the provided arguments.

The arguments are checked for deep equality and can also be matchers.

Because this validator does not print the actual received arguments in case of failure it is recommended to use one of the following matchers instead:

  • expect(fn).toHaveBeenOnlyCalledWith(...)
  • expect(fn).toHaveBeenLastCalledWith(...)
  • expect(fn).toHaveBeenNthCalledWith(time, ...)

Parameters:

  • args - The arguments the mock function was expected to be called with. They can also be matchers.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn = mockFn((a: number, b: number) => a + b)
fn(1, 2)
fn(3, 4)
expect(fn).toHaveBeenCalledWith(3, expect.a(Number))
expect(fn).not.toHaveBeenCalledWith(5, 6)

.toHaveBeenExhausted(this: Validators<MockFunction<any[], any>>): void

Asserts that the mock function was called enough so that all the specified one time overrides were used.

If no one time overrides were specified, this will always pass.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn = mockFn().returnsOnce(420).returnsOnce(69)
expect(fn).not.toHaveBeenExhausted()
fn() // returns 420
fn() // returns 69
expect(fn).toHaveBeenExhausted()

.toHaveBeenLastCalledWith(this: Validators<MockFunction<any[], any>>, ...args: MockParameters<T>): void

Asserts that when the mock function was called the last time it was called with the given arguments. If the function was never called this will fail.

The arguments are checked for deep equality and can also be matchers.

If you would like to assert that the function was only called once use expect(fn).toHaveBeenOnlyCalledWith(...) instead.

Parameters:

  • args - The arguments the mock function was expected to be called with. They can also be matchers.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn = mockFn((a: string, b: string) => a + ' ' + b)
fn('i like', 'pancakes')
fn('you like', 'waffles')

expect(fn).toHaveBeenLastCalledWith('you like', expect.a(String))
expect(fn).not.toHaveBeenLastCalledWith('i like', 'pancakes')

.toHaveBeenNthCalledWith(this: Validators<MockFunction<any[], any>>, n: number, ...args: MockParameters<T>): void

Asserts that when the mock function was called the nth time it was called with the given arguments. If the function was called less than n times this will fail.

The arguments are checked for deep equality and can also be matchers.

If you would like to always check the last call use expect(fn).toHaveBeenLastCalledWith(...) instead.

Parameters:

  • n - The call number to check the arguments of. Index starts at 1.
  • args - The arguments the mock function was expected to be called with the nth time. They can also be matchers.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn = mockFn((a: string, b: string) => a + ' ' + b)
fn('i like', 'pancakes')
fn('you like', 'waffles')

expect(fn).toHaveBeenNthCalledWith(1, 'i like', expect.a(String))
expect(fn).toHaveBeenNthCalledWith(2, 'you like', 'waffles')
expect(fn).not.toHaveBeenNthCalledWith(2, 'you like', 'pancakes')

.toHaveBeenOnlyCalledWith(this: Validators<MockFunction<any[], any>>, ...args: MockParameters<T>): void

Asserts that the mock function was called exactly once and with the provided arguments.

The arguments are checked for deep equality and can also be matchers.

If you don't care that the function was only called once use expect(fn).toHaveBeenNthCalledWith(1, ...) instead.

Parameters:

  • args - The arguments the mock function was expected to be called with. They can also be matchers.

Examples:

ts
import { expect, mockFn } from 'earl'

const fn1 = mockFn((a: number, b: number) => a + b)
fn1(1, 2)
expect(fn1).toHaveBeenOnlyCalledWith(1, expect.a(Number))

const fn2 = mockFn((a: number, b: number) => a + b)
fn2(1, 2)
fn2(3, 4)
expect(fn2).not.toHaveBeenOnlyCalledWith(1, 2)

.toHaveLength(this: Validators<string | any[] | { length: number

Asserts that a string, array or object with a length property has a specific length.

If you want to match a nested value, use the matcher expect.length(length) instead.

Parameters:

  • length - The expected length. Can be a matcher.

Examples:

ts
expect('abcdef').toHaveLength(6)
expect([1, 2, 3]).toHaveLength(expect.greaterThan(2))

expect({ length: 5 }).not.toHaveLength(4)

.toHaveSubset(this: Validators<object>, subset: Subset): void

Asserts that an object contains the given key value pairs.

If you want to match a nested value, use the matcher expect.subset(subset) instead.

Parameters:

  • subset - The expected key-value pairs that the object has.

Examples:

ts
const response = await api.get('/users/me')
expect(response).toHaveSubset({
  success: expect.a(Boolean),
  data: expect.subset({
    name: 'John Doe',
    age: 42,
  }),
})

.toInclude(this: Validators<any[] | Set<any> | Iterable<any>>, ...items: MemberOf<T>[]): void

Asserts that an array, set or iterable includes all of the provided items.

If you want to match a nested value, use the matcher expect.includes(...) instead.

Parameters:

  • items - The items to look for. Can be matchers.

Examples:

ts
expect([1, 'foo', false]).toInclude(expect.a(Boolean), 'foo')
expect(new Set([5, 6])).toInclude(5)

// type-error: type string is not assignable to boolean
expect([true, false]).not.toInclude('magic')

.toInclude(this: Validators<string>, ...substrings: string[]): void

Asserts that a string includes all of the provided substrings. The substrings can overlap.

If you want to match a nested value, use the matcher expect.includes(...) instead.

Parameters:

  • substrings - The substrings to look for. Cannot be matchers.

Examples:

ts
expect('i like pancakes').toInclude('like', 'cakes')
expect('animals').toInclude('ani', 'nim', 'mal')

expect('robot').not.toInclude('cupcake')

.toLooseEqual(this: Validators<object>, expected: unknown): void

Asserts that a value is loosely equal to another value. The equality is checked using recursively, but ignoring object prototypes.

This validator also supports asymmetric matchers on the expected value.

This validator shouldn't be used for primitives. Use toEqual instead.

Unlike toEqual this validator does not also work on the type level.

If you would like instead to check values for referential equality use the toExactlyEqual validator instead.

Parameters:

  • expected - The expected value. Can include nested matchers.

Examples:

ts
expect(new Vector2(5, 7)).toLooseEqual({
  x: 5,
  y: expect.greaterThan(0),
})

.toMatchRegex(this: Validators<string>, regex: RegExp): void

Asserts that the value is a string matching the given regular expression.

If you want to match a nested value, use the matcher expect.regex(regex) instead.

Parameters:

  • regex - The regular expression to test the matched values.

Examples:

ts
expect('I like pancakes').toMatchRegex(/like/)

expect('foo').not.toMatchRegex(/^d+$/)

.toMatchSchema(schema: ZodSchema): void

Asserts that the value conforms to the provided zod schema.

If you want to match a nested value, use the matcher expect.schema(schema) instead.

Parameters:

  • schema - The zod schema to use.

Examples:

ts
import * as z from 'zod'
const Pricing = z.object({
  price: z.number().positive(),
  currency: z.string().length(3),
})

expect({
  price: 1299,
  currency: 'USD',
}).toMatchSchema(Pricing)

expect({
  price: -1,
  currency: 'error',
}).not.toMatchSchema(Pricing)

.toMatchSnapshot(context: TestContext): void

Asserts that a value is equal to a snapshot. The first time the assertion is run, a snapshot is created. Subsequent runs will compare the value to the snapshot.

Snapshots are stored in the .snapshot files next to the test file.

To update all snapshots set the UPDATE_SNAPSHOTS environment variable to true.

Because earl is independent of the test runner it needs to have some information about the test context. This is provided by the context argument. In mocha the context is the this object. In uvu it is the context parameter.

Parameters:

  • context - The test context.

Examples:

ts
// mocha
it('snapshot', function () {
  // Important! use `function` instead of `() =>`
  // to have access to `this`.
  expect({ foo: 'bar' }).toMatchSnapshot(this)
})

// uvu
test('snapshot', (ctx) => {
  expect({ foo: 'bar' }).toMatchSnapshot(ctx)
})

.toSatisfy(predicate: (value: T) => boolean): void

Asserts that the provided predicate returns a truthy result for the given value.

Usually other validators are more appropriate, but this can be useful if you are testing something custom.

If you want to match a nested value, use the matcher expect.satisfies(predicate) instead.

Parameters:

  • predicate - The function for checking values.

Examples:

ts
function isShark(value: unknown) {
  return value instanceof Fish && value.species === 'shark'
}
expect(new Fish('Bobby', { species: 'shark' })).toSatisfy(isShark)

.toThrow(this: Validators<() => any>, errorClass: new (...args: any[]) => Error, message?: string | RegExp): void

Asserts that a function throws a given message and/or error class when called.

This validator does not support async functions. Use toBeRejected and toBeRejectedWith instead.

Parameters:

  • errorClass - The error class to check.
  • message - A substring of the error message or a regex matching the message.

Examples:

ts
// checking the error message with a substring
expect(() => {
  throw new Error('no pancakes found')
}).toThrow('pancakes')

// checking the error message with a regex
expect(() => {
  throw new Error('12345')
}).toThrow(/^\d+$/)

// checking the error class
expect(() => {
  throw new TypeError('magic')
}).toThrow(TypeError)

// checking the error class and message
expect(() => 1n / 0n).toThrow(RangeError, 'Division by zero')

.toThrow(this: Validators<() => any>, message?: string | RegExp): void

Asserts that a function throws a given message and/or error class when called.

This validator does not support async functions. Use toBeRejected and toBeRejectedWith instead.

Parameters:

  • message - A substring of the error message or a regex matching the message.

Examples:

ts
// just checking that the function throws
expect(() => {
  throw new Error('foo')
}).toThrow()

// checking the error message with a substring
expect(() => {
  throw new Error('no pancakes found')
}).toThrow('pancakes')

// checking the error message with a regex
expect(() => {
  throw new Error('12345')
}).toThrow(/^\d+$/)

// checking the error class
expect(() => {
  throw new TypeError('magic')
}).toThrow(TypeError)

// checking the error class and message
expect(() => 1n / 0n).toThrow(RangeError, 'Division by zero')

Matchers

expect.a<T extends NewableOrPrimitive>(type: T): never

Matches an instance of a provided class or a primitive type. It is compatible with built-in types like strings, numbers, and dates.

Using this matcher is recommended when you don't care about the exact value as long as it matches a given type.

If you want to match a top level value, use expect(...).toBeA(type) instead.

Parameters:

  • type - The class or primitive constructor to match against.

Examples:

ts
// Primitives
expect({ foo: Math.random() }).toEqual({ foo: expect.a(Number) })

// Classes
expect({
  employee: new Employee('John Doe', 42),
  birthday: new Date('1990-01-01'),
}).toEqual({
  employee: expect.a(Employee),
  birthday: expect.a(Date),
})

expect.anything(): never

Matches any value.

Using this matcher is recommended when you want to ensure that a key is present on an object, but you don't care about its value.

Examples:

ts
const person = findPerson('John Doe')
expect(person).toEqual({
  name: 'John Doe',
  favoriteThing: expect.anything(),
})

expect.between(min: number | bigint, max: number | bigint): never

Matches numbers that are between the two numbers. The range is [min, max], inclusive on both sides.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeBetween(min, max) instead.

Parameters:

  • min - The minimum value, inclusive.
  • max - The maximum value, inclusive.

Examples:

ts
const location = getLatLon()
expect(location).toEqual({
  lat: expect.between(-90, 90),
  lon: expect.between(-180, 180),
})

expect.closeTo(target: number, delta: number): never

Matches numbers that are close to the target value. The range is [target - delta, target + delta], inclusive on both sides.

Works only for numbers and not for bigints.

If you want to match a top level value, use expect(...).toBeCloseTo(target, delta) instead.

Parameters:

  • target - The number to aim for.
  • delta - The maximum difference between the values.

Examples:

ts
const vector = getApproximateStrikeTarget()
expect(vector).toEqual({
  x: expect.closeTo(420, 0.001),
  y: expect.closeTo(69, 0.001),
})

expect.defined(): never

Matches values that are not undefined.

If you want to match a top level value, use expect(...).not.toEqual(undefined) instead.

Examples:

ts
const result = await fetchStockPrices('BANANA', 'KIWI')
expect(result).toEqual({
  BANANA: expect.defined(),
  KIWI: expect.defined(),
})

expect.empty(): never

Matches empty strings, arrays, sets and maps.

If you want to match a top level value, use expect(...).toBeEmpty() instead.

Examples:

ts
const sadGuy = await people.findWhere({ friendCount: 0 })
expect(sadGuy).toEqual({
  name: 'John Doe',
  friends: expect.empty(),
})

expect.falsy(): never

Matches falsy values, as defined by: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

You can also use its sister matcher, truthy, to match the opposite.

If you want to match a top level value, use expect(...).toBeFalsy() instead.

Examples:

ts
const doggy = dogApi.getDog('Waffles')
expect(doggy).toEqual({
  name: 'Waffles',
  // Waffles is a stray, we don't know the date :(
  birthday: expect.falsy(),
})

expect.greaterThan(target: number | bigint): never

Matches numbers that are greater than the given target.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeGreaterThan(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect({
  salary: 100_000,
  bonus: 10_000,
}).toEqual({
  salary: expect.greaterThan(50_000),
  bonus: expect.greaterThan(5_000),
})

expect.greaterThanOrEqual(target: number | bigint): never

Matches numbers that are greater than or equal to the given target.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeGreaterThanOrEqual(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect({
  salary: 100_000,
  bonus: 5_000,
}).toEqual({
  salary: expect.greaterThanOrEqual(50_000),
  bonus: expect.greaterThanOrEqual(5_000),
})

expect.includes(...items: any[]): never

Matches an array, Set or iterable that includes the given item or items. Also matches a string that includes the given substring or substrings.

If you want to match a top level value, use expect(...).toInclude(...items) instead.

Parameters:

  • items - Items or matchers to look for. When the value is a string, all items must be strings too.

Examples:

ts
expect({
  numbers: [1, 2, 3],
  mixed: [1, 'foo', false],
  string: 'I like pancakes',
}).toEqual({
  numbers: expect.includes(1, 2),
  mixed: expect.includes(1, expect.a(String)),
  string: expect.includes('pancakes'),
})

expect.integer(): never

Matches numbers that are integers.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeAnInteger() instead.

Examples:

ts
const counts = getParticleCounts()
expect(counts).toEqual({
  min: 0,
  max: expect.integer(),
  median: expect.integer(),
})

expect.length(length: number): never

Matches an array, string or any object with a length property that has the given length.

If you want to match a top level value, use expect(...).toHaveLength(length) instead.

Parameters:

  • length - The expected length. Can be a matcher.

Examples:

ts
expect({
  numbers: [1, 2, 3],
  letters: 'abcdef',
}).toEqual({
  numbers: expect.length(3),
  letters: expect.length(expect.greaterThan(3)),
})

expect.lessThan(target: number | bigint): never

Matches numbers that are less than the given target.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeLessThan(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect({
  salary: 100_000,
  bonus: 10_000,
}).toEqual({
  salary: expect.lessThan(200_000),
  bonus: expect.lessThan(20_000),
})

expect.lessThanOrEqual(target: number | bigint): never

Matches numbers that are less than or equal to the given target.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeLessThanOrEqual(target) instead.

Parameters:

  • target - The target value to compare to.

Examples:

ts
expect({
  salary: 100_000,
  bonus: 20_000,
}).toEqual({
  salary: expect.lessThanOrEqual(200_000),
  bonus: expect.lessThanOrEqual(20_000),
})

expect.notEmpty(): never

Matches strings, arrays, sets and maps that aren't empty.

If you want to match a top level value, use expect(...).not.toBeEmpty() instead.

Examples:

ts
const happyGuy = await people.findWhere({ friendCount: 42 })
expect(happyGuy).toEqual({
  name: 'John Doe',
  friends: expect.notEmpty(),
})

expect.notNullish(): never

Matches values that are not nullish, i.e. values that are not null or undefined.

If you want to match a top level value, use expect(...).not.toBeNullish() instead.

Examples:

ts
const result = await fetchStockPrices('BANANA', 'KIWI')
expect(result).toEqual({
  BANANA: expect.notNullish(),
  KIWI: expect.notNullish(),
})

expect.nullish(): never

Matches null and undefined.

If you want to match a top level value, use expect(...).toBeNullish() instead.

Examples:

ts
const result = await flight.getPassenger('17A')
expect(result).toEqual({
  name: 'John Doe',
  seat: '17A',
  insurancePolicy: expect.nullish(),
})

expect.property(key: string, value?: unknown): never

Matches objects for which a given key exists. Optionally checks the property value.

Parameters:

  • key - The expected property key.
  • value - (optional) The expected property value.

Examples:

ts
const events = await getLatestEvents({ limit: 3 })
expect(events).toEqual([
  expect.property('pending', true),
  expect.property('finalizedAt'),
  expect.property('finalizedAt'),
])

expect.regex(regex: RegExp): never

Matches strings that match the given regular expression.

If you want to match a top level value, use expect(...).toMatchRegex(regex) instead.

Parameters:

  • regex - The regular expression to test the matched values.

Examples:

ts
const contact = await customer.getUSContactInfo()
expect(contact).toEqual({
  state: expect.regex(/^[A-Z]{2}$/),
  zipCode: expect.regex(/^\d{5}$/),
  phoneNumber: expect.regex(/^\d{3}-\d{3}-\d{4}$/),
})

expect.safeInteger(): never

Matches numbers that are integers between Number.MIN_SAFE_INTEGER nad Number.MAX_SAFE_INTEGER.

Works for both numbers and bigints.

If you want to match a top level value, use expect(...).toBeASafeInteger() instead.

Examples:

ts
const counts = getExperimentStats()
expect(counts).toEqual({
  min: 0,
  max: expect.safeInteger(),
  median: expect.safeInteger(),
})

expect.satisfies(predicate: (value: unknown) => boolean): never

Matches values for which the predicate returns a truthy value.

Usually other matchers are more appropriate, but this can be useful if you are testing something custom.

If you want to match a top level value, use expect(...).toSatisfy(predicate) instead.

Parameters:

  • predicate - The function for checking values.

Examples:

ts
function isShark(value: unknown) {
  return value instanceof Fish && value.species === 'shark'
}
expect(crazyZoologist).toEqual({
  name: 'John Doe',
  pet: expect.satisfies(isShark),
})

expect.schema(schema: ZodSchema): never

Matches values conforming to the provided zod schema.

If you want to match a top level value, use expect(...).toMatchSchema(schema) instead.

Parameters:

  • schema - The zod schema to use.

Examples:

ts
import * as z from 'zod'
const product = await getLatestProduct()
expect(product).toEqual({
  name: 'Turbocharger 9000',
  uuid: expect.schema(z.string().uuid()),
  pricing: expect.schema(
    z.object({
      price: z.number().positive(),
      currency: z.string().length(3),
    }),
  ),
})

expect.subset(subset: Subset): never

Matches an object containing the given key value pairs.

If you want to match a top level value, use expect(...).toHaveSubset(subset) instead.

Parameters:

  • subset - The key value paris to match against.

Examples:

ts
const response = await api.get('/users/me')
expect(response).toEqual({
  success: true,
  data: expect.subset({
    name: 'John Doe',
    age: 42,
  }),
})

expect.truthy(): never

Matches truthy values, as defined by: https://developer.mozilla.org/en-US/docs/Glossary/Truthy

You can also use its sister matcher, falsy, to match the opposite.

If you want to match a top level value, use expect(...).toBeTruthy() instead.

Examples:

ts
const kitty = catApi.getCat('Peanut')
expect(kitty).toEqual({
  name: 'Peanut',
  // they are a happy family, but we don't care about the details
  mom: expect.truthy(),
  dad: expect.truthy(),
})

Mocks

function mockFn<F extends (...args: any) => any>(defaultImplementation?: F): MockFunctionOf<F>

Creates a mock function conforming to a given signature. You can call methods on the mock function to further customize its behavior.

Without a default implementation and without any further configuration the mock will throw an error when called.

Parameters:

  • defaultImplementation - (optional) A default implementation to use when the mock is called.

Examples:

ts
const mock1 = mockFn((a: number, b: string) => a + b.length)

const mock2 = mockFn<(a: number, b: string) => number>()
const mock3 = mockFn<[number, string], number>()

const mock4 = mockFn().returnsOnce(420).returns(69)

Released under the MIT License.