Elegant jest.expect typings for a more civilized age

Overview

typed-jest-expect

Elegant jest.expect typings for a more civilized age

Why?

By default, the expect utility of jest is very broadly typed, which makes sense for a testing library, and doesn't complain when you do something like that:

expect(42).toEqual("definitely not 42");

However, when your codebase is mostly well-typed internally, you don't benefit from TypeScript as much as you could, specifically:

  1. static warnings for obvious errors suchs as typos,
  2. editor auto-completion.

This missed opportunity impedes productivity.

This library re-exports expect with much stronger typings: you can only test equality with assignable values, use function assertions with Jest mocked functions, use number comparison with numbers and BigInts, etc.

It prevents you from writing code such as:

tExpect(42).toEqual("definitely not 42");
tExpect({
  x: 42,
}).toEqual({
  y: 77,
});

And conversely, auto-completion now works correctly:

tsExpect({
  foo: "bar",
  fizz: "buzz",
}).toMatchObject({
  fizz: "bu...", // auto-complete
});

Installation

npm i typed-jest-expect
import { tExpect } from "typed-jest-expect";

tExpect([1, 3, 2]).toContain(3);

This library has virtually 0 runtime cost. The emitted JS code does nothing but re-exporting the global expect function:

"use strict";
Object.defineProperty(exports, "__esModule", {
  value: true,
});
exports.tExpect = void 0;
const tExpect = (t) => expect(t);
exports.tExpect = tExpect;

Since it doesn't change the original expect typings, you can still use the broadly-typed original expect for interacting with code that is not fully typed:

tExpect(42).toEqual(42);
expect(notSureWhatThisShouldReturn()).toEqual("1337");

Examples of invalid code statically rejected by tExpect

// Calling .resolves or .rejects on non-promise
tExpect(0).resolves; // never
tExpect(Promise.resolve(0)).resolves.toEqual(0);

// Calling toBe / toEqual / toMatchObject with incompatible values
tExpect({ foo: "bar" }).toEqual({ foo: 42 } /* never */);

// toBeCalled on anything that is not a mocked function
tExpect(42).toBeCalled; // never
tExpect(() => 42).toBeCalled; // never
tExpect(jest.fn(() => 42)).toBeCalled();

// toBeCalledWith with non-assignable parameters
const sum = jest.fn((a: number, b: number): number => a + b);
tExpect(sum).toBeCalledWith("a" /* never */, 3);

// toHaveReturnedWith with non-assignable return value
tExpect(sum).toHaveReturned(null /* never */);

// toHaveLength with anything that doesn't have a .length number property
tExpect({}).toHaveLength; // never

// toHaveProperty with a non-existent property key
tExpect({ foo: "bar" }).toHaveProperty("fizz", "bar" /* never */);

// toBeCloseTo, toBeGreaterThan, etc., with non-number / BigInt
tExpect("32").toBeGreaterThan; // never

// toBeDefined on non-optional types
tExpect(42).toBeDefined; // never
tExpect(true ? 42 : undefined).toBeDefined(); // ok

// toBeInstanceOf on non-assignable constructors
class Animal {
  kind: string;
  constructor(kind: string) {
    this.kind = string;
  }
}
tExpect({ species: "dog" }).toBeInstanceOf(Animal /* never */);

// toBeNull on non-nullable types
tExpect(42).toBeNull; // never
tExpect(true ? 42 : null).toBeNull(); // ok (throws though)

// toThrow on non-functions, or functions with parameters
tExpect((a: number, b: number) => {}).toThrow; // never
You might also like...

✨ Elegant portfolio template built on NextJS and Tailwind.

✨ Elegant portfolio template built on NextJS and Tailwind.

Obsidian ✨ Obsidian is a minimal and lightweight portfolio template built on NextJS and TailwindCSS. ✨ Setup Install the dependencies Edit content Cha

Dec 21, 2022

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions

The invoker based on event model provides an elegant way to call your methods in another container via promisify functions. (like child-processes, iframe, web worker etc).

Dec 29, 2022

Chat View let's you quickly and easily create elegant Chat UIs in your Markdown Files.

Chat View let's you quickly and easily create elegant Chat UIs in your Markdown Files.

Obsidian Chat View Plugin Chat View let's you quickly and easily create elegant Chat UIs in your Markdown Files. Usage Every chat message must be pref

Dec 27, 2022

A Powerful and Elegant "alert" library for JavaScript that replaces that boring alert style of Javascript.

A Powerful and Elegant

A Powerful , Elegant and fully customizable "alert" library using JavaScript that replaces that boring style of alert. Installation Place the below sc

Aug 10, 2021

An elegant console logger.

An elegant console logger.

kons An elegant console logger. Features Tiny (Minified + Gzipped ≈ 0.1kB). Beautiful. Easy to use. Customizable. TypeScript type declarations include

Aug 13, 2022

Pure JavaScript HTML5 Canvas Range Slider. No stylesheet needed. Simple, elegant and powerful. A quirky alternative to other sliders.

Pure JavaScript HTML5 Canvas Range Slider. No stylesheet needed. Simple, elegant and powerful. A quirky alternative to other sliders.

CanvasSlider CanvasSlider is a lightweight JavaScript range slider. Most of the range slider controls use Javascript and a stylesheet. This slider use

Aug 15, 2022

🚀Starter project with Angular 13, Ngx-admin, NestJS, Nx Workspace, Jest, Cypress, ESLint & Prettier 🚀

🚀Starter project with Angular 13, Ngx-admin, NestJS, Nx Workspace, Jest, Cypress, ESLint & Prettier 🚀

Angular 13 + Ngx-admin + NestJs + NX Starter project with Angular 13, Ngx-admin, NestJs, Nx Workspace, Jest, Cypress, ESLint & Prettier Features ✅ Ang

Jan 4, 2023

API em NodeJS, utilizando banco de dados MongoDB (TypeORM), com cobertura de testes (coverages), utilizando o Jest

API em NodeJS, utilizando banco de dados MongoDB (TypeORM), com cobertura de testes (coverages), utilizando o Jest

Api Backend Tindin Sobre API em NodeJS, utilizando banco de dados MongoDB (TypeORM), com cobertura de testes (coverages), utilizando o Jest. 👉 app ur

Jan 20, 2022

Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK

Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK

serverless dynamodb integration tests 🚀 Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK Introduction How to inte

Nov 4, 2022
Owner
Elie Rotenberg
Former founder / CTO at millenium.org / jeuxvideo.com Founder / CTO at ifea.education
Elie Rotenberg
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A complete and heavily tested wrapper with typings for the zapper.fi API.

Zapperfi API Unofficial wrapper for the Zapperfi API Don't forget to leave a ⭐ if you found this useful. Install # use npm $ npm i zapperfi-api # use

izayl 6 Sep 4, 2022
Automatically document all of your Remix loaders and actions typings per each route. 📚

About remix-docs-gen parses all of your Remix loaders and actions and automatically documents all the typings per each route. Installation First, you

Stratulat Alexandru 50 Nov 9, 2022
🥾 A simple way to do testing AWS Services and Jest or Serverless and Jest

jest-localstack-preset Install Install via yarn or npm $ yarn add https://github.com/thadeu/jest-localstack-preset.git or $ npm i https://github.com/t

thadeu 5 Oct 1, 2022
Create HTML from CSS! A modern javascript library you'd expect Facebook to invent.

Create HTML from CSS! A modern javascript library you'd expect Facebook to invent. Slowly build modern websites without ever leaving your CSS, with HeadwindHTML

Gökhan Mete ERTÜRK 282 Dec 30, 2022
CLI tool to add @ts-expect-errors to typescript type errors

suppress-ts-errors Cli tool to add comments to suppress typescript type errors. Add @ts-expect-error or @ts-ignore comments to all locations where err

ryo 53 Dec 8, 2022
Displaying actual age in percentage with 9 signs after dot (floating number)

Actual Age Chrome Extension Displaying actual age in percentage with 9 signs after dot (floating number) Features Popup You can select your Birth date

Igor Makeenko 22 Nov 2, 2022
Weather Condition App is a mobile application that has a category of countries in the home age and the users can access to weather of each country.

World Weather This is a SPA react-app project that is built using two APIs. And users can select and choose countries and states and get their updated

Ahmad Zamir Yousufi 2 Oct 10, 2022
A simple boilerplate using NextJS, Typescript, Tailwind, Jest, Storybook and more.

This is a Next.js boilerplate using TailwindCSS and other cool stuff. Most of this is taught in this course. What is inside? This project uses lot of

React Avançado 26 Dec 4, 2022