Coder Social home page Coder Social logo

ts-state-test-generator's Introduction

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.

ts-state-test-generator's People

Contributors

dsherret avatar

Stargazers

Valeri Vicneanschi avatar

Watchers

James Cloos avatar  avatar  avatar

ts-state-test-generator's Issues

Add helper writer functions

Add functions for helping with writing tests. For example, add a function to write a describe or it call.

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.