Code Monkey home page Code Monkey logo

ts-snippet's Introduction

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. However, if you've not yet started writing tests for your TypeScript types, you should look at using tsd instead.

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;
}

ts-snippet's People

Contributors

cartant avatar dolsem avatar greenkeeper[bot] avatar hasparus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

dolsem hasparus

ts-snippet's Issues

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.11.0 to 12.11.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: build: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Should `.toInfer` automatically check `.toSucceed()` as well?

Hey Nicholas.

I ran into interesting scenario, where the returned value was still inferred "correctly", however the inner callback was failing.

e.g.

Error snippet.ts (21,86): Cannot find name 'Loading'.

      228 |         expectSnippet(
      229 |           `const sub = componentStore.updater((state, v: LoadingState) => ({...state}))(Loading.LOADED);`
    > 230 |         ).toSucceed();

However, if I just have .toInfer(...) then the test passes.

expectSnippet(
          `const sub = componentStore.updater((state, v: LoadingState) => ({...state}))(Loading.LOADED);`
        ).toInfer('sub', 'Subscription');

no problem there.

Should .toInfer automatically check .toSucceed as well? e.g. I was expecting tests to be failing.

Printing the actual error value in `toFail`

Hey @cartant! Thanks for this package. I have no idea how would I test inference in Theme UI without it 🙏

I have one problem, though. Every time my error doesn't match, I have to change toFail to toSucceed to see its value.

current

image

expected

Expected an error matching ___ and instead received ___

Provide more useful error output

Using expectSnippet, when the expected error fails using toFail, the developer does not know what errors actually did occur.

Would it be possible to output the errors that were found, or even attempt to show an error with the closest matching string?

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 10.12.8 to 10.12.9.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.7.12 to 12.11.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ci/circleci: build: Your tests failed on CircleCI (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.6.9 to 12.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.