Skip to content

A type-safe fluent assertion library written in TypeScript and inspired by Jest assertions and the popular AssertJ

License

Notifications You must be signed in to change notification settings

stackbuilders/assertive-ts

Repository files navigation

All Contributors

CI Release Pages NPM Core version NPM Sinon version NPM license Known Vulnerabilities

Assertive.ts

A type-safe fluent assertion library written in TypeScript and inspired by Jest assertions and the popular AssertJ.

This library is designed to work in the browser and in Node.js. It ships with a rich set of expressive and flexible matchers that allows chaining multiple assertions. Assertive.ts is framework agnostic and should be used with a test framework such as Jest, Mocha, or Ava.

🚨 BREAKING CHANGES: Since v2, the @stackbuilders/assertive-ts package has been renamed to @assertive-ts/core so we can group other packages, such as plugins, into the same namespace. Check the packages section for more info.

Type-safe library

A distinctive feature of Assertive.ts with other assertion libraries is that it leverages the TypeScript compiler to avoid type coercions and mismatches. It also infers the static type of the value you want to assert and provides you with intelligent matcher completion and signature help so that you can write code more quickly and correctly.

Features

  • Type safety and intelligent matcher completion
  • Rich set of expressive and flexible matchers
  • Concise, chainable interface inspired by AssertJ
  • Works with any test runner and framework such as Jest, Mocha, or Ava
  • Well tested: more than 300 tests!

Packages

For convenience, this library is split into packages grouped within the same namespace:

  • assertive-ts/core: Core functionalities, assertions applicable for any kind of application. This package is required for the extension mechanism (plugins). This package replaces the deprecated stackbuilders/assertive-ts package.
  • assertive-ts/sinon: Plugin to add matchers for Sinon.js spies, stubs, mocks, and fakes.

Usage

Using you favorite test runner, you just need to import the expect and test away! If you don't really agree with expect as the name of the assertion function, we provide a couple aliases, such as assert and assertThat.

import { expect } from "@assertive-ts/core";

describe("sum", () => {
  it("returns the sum of two numbers", () => {
    const result = sum(3, 2);

    expect(result).toBeEqual(5);
  });
});

To assert the opposite, you can simply use the .not modifier before the matcher:

expect(sum(1, 2)).not.toBeNull();

This library provides fluent assertions, which means you can chain multiple matcher functions to the same value under test:

expect("assertive-ts is awesome!")
  .toStartWith("assertive-ts")
  .not.toContain("unsafe")
  .toEndWith("awesome!");

The matcher functions depend on the type of the value on the expect. If you're using TypeScript, the compiler will let you know if something is not available for that assertion:

// Boolean assertion
expect(isEven(2)).toBeTrue();

// String assertion
expect("foobar").toStartWith("foo");

// Number assertion
expect(sum(1, 2)).toBePositive();

// Error assertion
expect(new Error(errorMessage)).toHaveMessage(expectedError);

// Array assertion
const data = [1, 2, 3, 4]
expect(data).toMatchAll(x => x < 5);
expect(data).toBeEmpty()

// Date assertion
const date = new Date(2023, 12, 31);
expect(date).toBeAfter(new Date(2023, 12, 1));
expect(date).toBeBefore(new Date(2024, 1, 1));

// Object assertion
const objectData = {
  key1: "test1",
  key2: "test2",
};
expect(objectData).toContainKey("key1");
expect(objectData).toContainEntry(["key1", "test1"]);

expect(14).toEndWith("4");
           ^ ? type error: `toEndWith` does not exist in `NumberAssertion`

You can also assert over functions and asynchronous code, for example:

function verifyEnvVar(): void {
  const { MY_ENV_VAR } = process.env;

  if (!MY_ENV_VAR) {
    throw new Error("Missing MY_ENV_VAR environment variable");
  }
};

// assertion
expect(() => verifyEnvVar())
  .toThrowError(Error)
  .toHaveMessage("Missing MY_ENV_VAR environment variable");

expect(() => verifyEnvVar()).not.toThrow();

async function getData(): Promise<DataType> {
  const data = await requestApi();

  if (!data) {
    throw new Error("Data was not found");
  }

  return data;
}

// assertion
await expect(getData()).toBeRejected();

await expect(getData()).toBeResolved();

For a list of all Core matchers and extended documentation, you can refer to the Core API documentation.

Test Runner Integration

Assertive.ts works on any JavaScript test runner, both on Node.js and browser environments. Below you can find some example of how to use it on some of the most common test runners:

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Jose Luis Leon
Jose Luis Leon

💻 🚇 🚧 📦 ⚠️
Byron Motoche
Byron Motoche

💻 ⚠️ 👀
Alejandro Vivanco
Alejandro Vivanco

💻 ⚠️ 👀
David Villamarin
David Villamarin

💻 ⚠️ 📖 👀
Alexander Mejía
Alexander Mejía

💻 ⚠️
Christian Samaniego
Christian Samaniego

📖 💻 ⚠️ 👀
Sebastián Estrella
Sebastián Estrella

🚇
Daniel Calle
Daniel Calle

🚇
Anthony Suárez
Anthony Suárez

📖
Sebastian Avalos
Sebastian Avalos

👀

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT, see the LICENSE file.

Contributing

Do you want to contribute to this project? Please take a look at our contributing guidelines to know how you can help us build it. You can also check the development guide for information about local setup and the release process.


Stack Builders

Check out our libraries | Join our team