0.3.1 • Published 7 years ago

ts-state-test-generator v0.3.1

Weekly downloads
3
License
MIT
Repository
github
Last release
7 years ago

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.
0.3.1

7 years ago

0.3.0

7 years ago

0.2.0

7 years ago

0.1.15

7 years ago

0.1.14

7 years ago

0.1.13

7 years ago

0.1.12

7 years ago

0.1.11

7 years ago

0.1.10

7 years ago

0.1.9

7 years ago

0.1.8

7 years ago

0.1.7

7 years ago

0.1.6

7 years ago

0.1.5

7 years ago

0.1.4

7 years ago

0.1.3

7 years ago

0.1.2

7 years ago

0.1.1

7 years ago

0.1.0

7 years ago