npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ts-state-test-generator

v0.3.1

Published

Generates tests for checking the state of a class or interface.

Downloads

6

Readme

TsStateTestGenerator

Build Status Coverage Status experimental

npm install --save-dev ts-type-info
npm install --save-dev ts-state-test-generator

This tool code generates test helper functions that test the state of an object based on its type information. It's currently experimental and subject to change.

Benefits

  • Write and maintain less code. I replaced 2500 lines of code with 250 in one of my projects and discovered a few bugs in my previous test methods.
  • When your class or interface properties change, simply re-run the code generation process for updated code.
  • Get static typing in the expected object.
  • Expected object can be different than actual object.
  • Add default values for properties so they don't need to be provided in the expected object.
  • Mark properties as being "opt-in" so those properties will only be tested when you provide an expected value.
  • Provides the ability to manipulate the process along the way.

Supports

  • Union types.
  • Intersection types.
  • Array types.
  • Type parameters.

Example

TypeScript classes & interfaces to test

// src/models.ts
export * from "./models/Person";
export * from "./models/Note";

// src/models/Person.ts
import {Note} from "./Note";

export interface Person {
    name: string;
    notes: Note[];
}

// src/models/Note.ts
export interface Note {
    creationDate: Date;
    text: string;
    isPinned: boolean;
}

Code generate the test helpers (development script)

This will code generate a test helper file for the interfaces.

// generateTestHelpers.js
// I usually just do this in a javascript file so I don't need to compile it (it's just a development script)
const path = require("path");
const fs = require("fs");
const getInfoFromFiles = require("ts-type-info").getInfoFromFiles;
const TestGenerator = require("ts-state-test-generator").TestGenerator;

// get the info from the files using ts-type-info
const typeInfo = getInfoFromFiles([
    path.join(__dirname, "src/models.ts") // or provide each file individually in an array
], {
    compilerOptions: {
        strictNullChecks: true
    }
});

// potentially modify the values in typeInfo here
// ex: removing public properties whose name matches a certain pattern
// see the ts-type-info project for how to manipulate it

// get the interfaces and/or classes you want from typeInfo
const interfaces = [];
typeInfo.files.filter(f => f.fileName.indexOf("/Models/") >= 0).forEach(f => {
    interfaces.push.apply(interfaces, f.interfaces); // or use spread
});

// create the test generator
const generator = new TestGenerator();
// add any transforms
generator.addDefaultValue((prop, interfaceDef) => interfaceDef.name === "Note" && prop.name === "isPinned", "false"); // adds a default test value
generator.addDefaultValue(prop => prop.type.isArrayType(), "[]");
generator.addOptInPropertyTransform((prop, interfaceDef) => interfaceDef.name === "Note" && prop.name === "creationDate"); // makes this property so its only tested for when provided
// - there is also: addPropertyTransform, addTestStructureTransform, addCustomTestTransform. I need to work on how exactly I want those to work so those are subject to change
// - if you have any ideas about some other transform let me know

// get the test file
const testFile = generator.getTestFile(interfaces);

// add necessary imports to the file based on where you are going to place it
const modelNamedImports = interfaces.map(c => c.name);
// modelNamedImports.push("SomeOtherType"); // you could add additional imports here
testFile.addImport({
    namedImports: modelNamedImports.map(name => ({ name })),
    moduleSpecifier: "./../models"
});

// add a statement to remind people not to edit this file
testFile.onBeforeWrite = writer => writer.writeLine("/* tslint:disable */").writeLine("// AUTO GENERATED CODE - DO NOT EDIT!").newLine();

// write out the file
fs.writeFile(path.join(__dirname, "src/tests/testHelpers.ts"), testFile.write());

Using generated code

It's best to look at the generated code so you can get an idea about how to use it (there are more advanced ways to use it than shown here).

Here's an example:

// src/tests/someTest.ts
import {runPersonTests} from "./testHelpers";

describe("functionThatReturnsAPersonWithNoNotes", () => {
	const person = functionThatReturnsAPersonWithNoNotes();

	// tests for:
	// * name to be "David"
	// * notes to be [] (default value specified in code generation)
	runPersonTests(person, { name: "David" });
});

describe("functionThatReturnsAPersonWithOneNote", () => {
	const person = functionThatReturnsAPersonWithOneNote();

	// tests for:
	// * name to be "David"
	// * notes to have text "Hello there!"
	// * isPinned to be false (default value specified in code generation)
	// * does not test `creationDate` because that's an opt in property (would only test if provided in the expected object)
	runPersonTests(person, {
		name: "David",
		notes: [{
			text: "Hello there!"
		}]
	});
});

Todo

  • Object type support.
  • Interface implements support (but only for interfaces)
  • A union type with null or undefined as a possibility should make the structure optional then it should check for either null or undefined.
  • Fix tests.