Package detail

ts-snippet

cartant923MIT5.0.2

A TypeScript snippet testing library for any test framework

snippet, test, testing, typescript

readme

ts-snippet

GitHub License NPM version Build status dependency status devDependency Status peerDependency Status Greenkeeper badge

What is it?

ts-snippet is a TypeScript snippet compiler for any test framework.

It does not run the compiled snippets. Instead, it provides assertion methods that can be used to test the TypeScript programs compiled from the snippets.

Why might you need it?

I created the ts-snippet package out of the need to test overloaded TypeScript functions that have many overload signatures.

The order in which overload signatures are specified is critical and the most specific overloads need to be placed first - as TypeScript will match the first compatible overload signature.

Without using ts-snippet, it's simple to write tests that establish whether or not TypeScript code compiles, but it's more difficult to write tests that establish whether type inferences are correct (especially when any is involved) or whether types are intentionally incompatible (and generate compilation errors).

ts-snippet includes assertions that will verify whether inferred types are what's expected and whether compilation succeeds or fails.

If you need to perform similar assertions, you might find ts-snippet useful.

For an example of how ts-snippet can be used to write tests, checkout the research-spec.ts file in my ts-action repo.

Install

Install the package using npm:

npm install ts-snippet --save-dev

Usage

This simplest way to use ts-snippet is to create a snippet expectation function using expecter:

import { expecter } from "ts-snippet";

const expectSnippet = expecter();

describe("observables", () => {
  it("should infer the source's type", () => {
    expectSnippet(`
      import * as Rx from "rxjs";
      const source = Rx.Observable.of(1);
    `).toInfer("source", "Observable<number>");
  });
});

expecter can be passed a factory so that common imports can be specified in just one place. For example:

import { expecter } from "ts-snippet";

const expectSnippet = expecter(code => `
  import * as Rx from "rxjs";
  ${code}
`);

describe("observables", () => {
  it("should infer the source's type", () => {
    expectSnippet(`
      const source = Rx.Observable.of(1);
    `).toInfer("source", "Observable<number>");
  });
});

Alternatively, the package exports a snippet function that returns a Snippet instance, upon which assertions can be made.

The snippet function takes an object containing one or more files - with the keys representing the file names and the values the file content (as strings). The function also takes an optional Compiler instance - if not specified, a Compiler instance is created within the snippet call. With snippets that import large packages (such as RxJS) re-using the compiler can effect significant performance gains.

Using Mocha, the tests look something like this:

import { Compiler, snippet } from "ts-snippet";

describe("observables", () => {

  let compiler: Compiler;

  before(() => {
    compiler = new Compiler();
  });

  it("should infer the source's type", () => {
    const s = snippet({
      "snippet.ts": `
        import * as Rx from "rxjs";
        const source = Rx.Observable.of(1);
      `
    }, compiler);
    s.expect("snippet.ts").toInfer("source", "Observable<number>");
  });

  it("should infer the mapped type", () => {
    const s = snippet({
      "snippet.ts": `
        import * as Rx from "rxjs";
        const source = Rx.Observable.of(1);
        const mapped = source.map(x => x.toString());
      `
    }, compiler);
    s.expect("snippet.ts").toInfer("mapped", "Observable<string>");
  });
});

Compiler can be passed the TypeScript compilerOptions JSON configuration and root directory for relative path module resolution (defaults to process.cwd()).

new Compiler({
  strictNullChecks: true
}, __dirname); // Now module paths will be relative to the directory where the test file is located.

If the BDD-style expectations are not to your liking, there are alternate methods that are more terse.

When using ts-snippet with AVA or tape, the import should specify the specific subdirectory so that the appropriate assertions are configured and the assertions count towards the test runner's plan.

Using the tape-specific import and terse assertions, tests would look something like this:

import * as tape from "tape";
import { snippet } from "ts-snippet/tape";

tape("should infer Observable<number>", (t) => {
  t.plan(1);
  const s = snippet(t, {
    "snippet.ts": `
      import * as Rx from "rxjs";
      const source = Rx.Observable.from([0, 1]);
    `
  });
  s.infer("snippet.ts", "source", "Observable<number>");
});

For an example of how ts-snippet can be used, have a look at these tests in ts-action.

API

function expecter(
  factory: (code: string) => string = code => code,
  compilerOptions?: object,
  rootDirectory?: string
): (code: string) => Expect;

function snippet(
  files: { [fileName: string]: string },
  compiler?: Compiler
): Snippet;
interface Snippet {
  fail(fileName: string, expectedMessage?: RegExp): void;
  expect(fileName: string): Expect;
  infer(fileName: string, variableName: string, expectedType: string): void;
  succeed(fileName: string): void;
}

interface Expect {
  toFail(expectedMessage?: RegExp): void;
  toInfer(variableName: string, expectedType: string): void;
  toSucceed(): void;
}

changelog

5.0.2 (2020-12-03)

Changes

  • Indicate the absence of errors for failure expectations. (70754b3)

5.0.1 (2020-11-21)

Changes

  • Include the actual error(s) when a failure expectation's regular expression does not match. (55778a5)

5.0.0 (2020-10-28)

Breaking Changes

  • infer/toInfer implies succeed/toSucceed and will throw if there are compilation errors. (54e0819)

4.3.0 (2020-08-28)

Changes

  • Widen TypeScript peer range. (df3ef4e)

4.2.0 (2019-04-22)

Fixes

  • Add a Compiler signature to expecter to facilitate faster tests. (a3d9058)

4.1.1 (2019-04-22)

Fixes

  • Don't throw a TypeScript Diagnostic for options-related errors. (0467d0e)

4.1.0 (2019-03-28)

Features

  • Added a rootDirectory option. (b8c6411)

4.0.0 (2018-12-16)

Breaking Changes

3.1.2 (2018-07-31)

Build

  • Widen TypeScript peer semver to allow for version 3.0. (c036f9e)

3.1.1 (2018-04-28)

Fixes

  • placeholders: Add T0 to placeholders.ts, etc. (b54ba02)

3.1.0 (2018-04-28)

Features

  • placeholders: Add placeholders.ts so that snippets can import pre-declared placeholder types, constants and variables. (a95f9a0)

3.0.0 (2018-04-01)

Breaking Changes

  • TypeScript: Drop support for TypeScript 2.0. (8f19247)
  • expecter: Rename reuseCompiler to expecter. (0df6415)

2.1.0 (2018-03-30)

Features

  • Add reuseCompiler to simplify use. (90a6bce)

2.0.1 (2018-01-31)

Fixes

  • The infer expectation now supports variables in nested scopes. (fa054bd)

Changes

  • The distribution now includes CommonJS, ES5 and ES2015 files.

2.0.0 (2017-11-03)

Breaking Changes

  • Compiler: The compiler now takes JSON options rather than options that use TypeScript's enums, etc. (71d93a4)