What is @vitest/expect?
The @vitest/expect package is a part of the Vitest testing framework, designed to work seamlessly with its ecosystem. It provides a powerful expectation library that allows developers to write assertions for their tests. This package is particularly useful for unit and integration testing, offering a wide range of matchers and utilities to test the behavior of JavaScript code.
What are @vitest/expect's main functionalities?
Basic Expectations
Allows for basic equality checks, useful for asserting that a value matches an expected result.
expect(value).toBe(42);
Object and Array Matching
Enables deep equality checks for objects and arrays, as well as checking for the presence of an item in an array.
expect(object).toEqual({ key: 'value' });
expect(array).toContain(item);
Asynchronous Testing
Facilitates testing of asynchronous operations, allowing assertions on resolved values of promises.
await expect(Promise.resolve('value')).resolves.toBe('value');
Mocking and Spies
Supports the creation of mock functions and spies, enabling the testing of function calls and their arguments.
const mockFunction = vi.fn();
expect(mockFunction).toHaveBeenCalledTimes(1);
Other packages similar to @vitest/expect
jest
Jest is a well-known testing framework that includes its own expectation library, very similar to @vitest/expect. It offers a comprehensive suite of features for testing JavaScript code, including snapshot testing, global setup/teardown, and more. Compared to @vitest/expect, Jest is more established but also heavier, making @vitest/expect a lighter alternative for projects already using Vitest.
chai
Chai is an assertion library for node and the browser that can be paired with any testing framework. It offers a range of interfaces (expect, should, assert) that allow developers to write tests in a style that suits them best. Compared to @vitest/expect, Chai is more flexible in terms of integration but does not offer the same level of integration with the Vitest ecosystem.
expect
The expect package is another assertion library that provides a set of extensive matchers to write tests. It is lightweight and does not tie itself to a specific test runner. While it shares similar functionalities with @vitest/expect, it lacks the tight integration and specific optimizations for the Vitest environment.
@vitest/expect
Jest's expect matchers as a Chai plugin.
Usage
import * as chai from 'chai'
import {
JestAsymmetricMatchers,
JestChaiExpect,
JestExtend,
} from '@vitest/expect'
chai.use(JestExtend)
chai.use(JestChaiExpect)
chai.use(JestAsymmetricMatchers)