1.0.3 • Published 10 months ago

vitest-double v1.0.3

Weekly downloads
-
License
BSD-2-Clause
Repository
github
Last release
10 months ago

Table of Contents

Overview

vitest-double is a tiny helper that allows you to create the full or partial "double" of a typed object while keeping its original type signature.

About the name

Double as in doppelgänger and 'vitesse double' also means 'double speed' in French, It's a double pun.

Getting started

To add vitest-double to your project:

npm install -D vitest-double
yarn add -D vitest-double
pnpm add -D vitest-double
bun add -D vitest-double

Usage

Calling double<MyType>() will create a double instance with correct type signature:

import { double } from 'vitest-double';

// Mocking the Navigator browser object:
const navigator = double<Navigator>();

You can use Vitest's usual bells and whistles to mock a double partially:

import { vi, expect } from 'vitest';
import { double } from 'vitest-double';

// Example with HTMLElement type:
const element = double<HTMLElement>({
  hidden: false,
  focus: vi.fn(),
  removeAttribute: vi.fn(),
  removeEventListener: vi.fn(),
  setAttribute: vi.fn(),
  addEventListener: vi.fn()
});

// [something calls focus() on HTML element...]

expect(element.focus).toHaveBeenCalled();
expect(element).not.toHaveDirtyProperty('hidden');

Doubles can be used to mock fairly complex structures; here is an example of VSCode's API:

// vscode-shim.ts
import type * as vscode from 'vscode';

import { double } from 'vitest-double';

export const workspace = double<typeof vscode.workspace>({
  getConfiguration: vi.fn(() =>
    double<vscode.WorkspaceConfiguration>({
      get: vi.fn(() => {})
    })
  )
});

export const window = double<typeof vscode.window>({
  createOutputChannel: double<typeof vscode.window.createOutputChannel>(() =>
    double<vscode.LogOutputChannel>({
      clear: vi.fn(),
      onDidChangeLogLevel: vi.fn()
    })
  )
});

Register your shim in your Vite or Vitest configuration file and use it in your specs:

resolve: {
  alias: {
    vscode: resolve(process.cwd(), 'vscode-shim.ts');
  }
}

You can use doubles to mock pretty much every third-party API.

License

This project is licensed under BSD 2-Clause.

1.0.3

10 months ago

1.0.2

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago