• Stars
    star
    141
  • Rank 259,971 (Top 6 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created about 10 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

TypeScript Unit Testing Framework

tsUnit

Choose a Version!

  • If you need ES5 support, please use v2.0.10 view the README for v2.0.10
  • v2.0.11 onwards is targeted at ES2015 and above and uses Promises

tsUnit is a unit testing framework for TypeScript, written in TypeScript. It allows you to encapsulate your test functions in classes and modules.

Install via NuGet:

PM> Install-Package tsUnit 

Install via NPM

> npm i tsunit.external

NOTE: Version 2.0 has breaking changes, to improve re-use between different module systems. Please read the below to see how to use version 2.0.

tsUnit comes with...

  • Built-in assertion helpers

  • Built-in HTML or TAP output, or raw data

  • A test limiter that lets you click to re-play a test, or group of tests without re-running the whole suite (thanks to Paul Atryda)

  • An easy to use test-double generator

  • Support for async testing (Version >= 2.0.2)

Simple!

It is so easy, you don't even have to download and unzip anything. It is just one file, written in TypeScript... just add tsUnit.ts to your project.

Please start a discussion if you think a feature is missing or doesn't work as expected.

Example

Test modules look like this...

    import * as tsUnit from './Scripts/tsUnit/tsUnit';
    import * as Calculations from './Scripts/Calculations';
	
    export class SimpleMathTests extends tsUnit.TestClass {
	
        private target = new Calculations.SimpleMath();
	
        addTwoNumbersWith1And2Expect3() {
             var result = this.target.addTwoNumbers(1, 2);
	
            this.areIdentical(3, result);
        }
	
        addTwoNumbersWith3And2Expect5() {
            var result = this.target.addTwoNumbers(3, 2);
	
            this.areIdentical(4, result); // Deliberate error
        }
    }

Composing your test suite goes as follows...

    import * as CalculationsTests from './Scripts/CalculationsTests';

    // "The One Liner" - you can do this in multiple stages too
    var test = new tsUnit.Test(CalculationsTests).run().showResults('results');

The multi-line version is also available... in particular this is useful if you want to re-use the result (which you can display as HTML and retrieve TAP output from).

    // Create the test suite
    var test = new tsUnit.Test(CalculationsTests);

    // Run the test
    var result = test.run();

    // Display in the element with id="results"
    result.showResults('results');

To run without a browser, you can call test.run() and use the raw result data yourself...

    // Handle the results yourself...
    var result = new tsUnit.Test(CalculationsTests).run();
    
    var outcome = (result.errors.length === 0) ? 'Test Passed' : 'Test Failed';

Or you can use the TAP (Test Anything Protocol) output:

    // TAP output...
    var tap = new tsUnit.Test(CalculationsTests).run().getTapResults();
    
    console.log(tap);

Async testing

To support async tests you must use the TestAsync class and it's test.runAsync() method.

    import * as CalculationsTests from './Scripts/CalculationsTests';

    // "The One Liner" - you can do this in multiple stages too
    var test = new tsUnit.TestAsync(CalculationsTests).runAsync().then((result) => result.showResults('results'));

Your test classes do not need to change unless you are writing an async test:

    import * as tsUnit from './Scripts/tsUnit/tsUnit';
    import * as CalculationsAsync from './Scripts/CalculationsAsync';
	
    export class AsyncMathTests extends tsUnit.TestClass {
	
        private target = new CalculationsAsync.SimpleMath();
	
        addTwoNumbersAsynchronouslyWith1And2Expect3() {
            var promise = this.target.addTwoNumbers(1, 2);
	
            // return a promise:
            return promise.then((result) => {
                this.areIdentical(3, result);
            });
            
        }
    }

Note how the method from your CalculationsAsync module returns a promise that has to be resolved before the result can be checked.

In order to allow the test runner to detect when your code is finished, your test must be a chain of promises (using .then) and you must return the last promise in that chain.

The use of the => operator allows us to access this -- if you use functions here you must provide access to the this of your test class:

    import * as tsUnit from './Scripts/tsUnit/tsUnit';
    import * as CalculationsAsync from './Scripts/CalculationsAsync';
	
    export class AsyncMathTests extends tsUnit.TestClass {
	
        private target = new CalculationsAsync.SimpleMath();
	
        addTwoNumbersAsynchronouslyWith1And2Expect3() {
            var promise = this.target.addTwoNumbers(1, 2);
	
            // save this:
            var self = this;

            return promise.then(function (result) {
                self.areIdentical(3, result);
            });
            
        }
    }

Since your code is now asynchronous, you will also not be able to use this.throws() to check that your code threw an exception. If you want to check that your result is a rejected promise, use test code like this:

    import * as tsUnit from './Scripts/tsUnit/tsUnit';
    import * as CalculationsAsync from './Scripts/CalculationsAsync';
	
    export class AsyncMathTests extends tsUnit.TestClass {
	
        private target = new CalculationsAsync.SimpleMath();
	
        divideByZeroAsynchronouslyIsRejected() {
            var promise = this.target.divide(1, 0);

            // use both parameters of then, second is onRejected callback:
            return p.then(() => {
                this.fail("expected promise to be rejected, got success");
            }, (err:Error) => {
                this.areIdentical("division by zero", err.message);
            })
        }
    }

More options for async running

Since the one-liner gets a little bit out of hand, this is how a multiline version of the async runner looks.

    // Create the test suite
    var test = new tsUnit.TestAsync(CalculationsTests);

    // Run the test
    var promise = test.runAsync();

    // await the result and show it

    promise.then(function(result) {
        // Display in the element with id="results"
        result.showResults('results');
    });

To run without a browser, you can call test.runAsync() and use the raw result data yourself...

    // Handle the results yourself...
    var promise = new tsUnit.TestAsync(CalculationsTests).runAsync();
    
    promise.then(function(result) {
        var outcome = (result.errors.length === 0) ? 'Test Passed' : 'Test Failed';
    });

Or you can use the TAP (Test Anything Protocol) output:

    // TAP output...
    // Handle the results yourself...
    var promise = new tsUnit.TestAsync(CalculationsTests).runAsync();

    promise.then(function(result) {
        var tap = result.getTapResults();
    
        console.log(tap);
    }

Remember, since the tests are run asynchronously, the results can only be delivered asynchronously.

License

Copyright 2012-2016 Steve Fenton, async support was written by and is Copyright 2016 Harald Niesche

Please read the LICENSE file for more details.

More Repositories

1

TypeSpec

An experimental TypeScript BDD framework.
TypeScript
41
star
2

TypeScriptUtilities

Some handy utilities I wrote in TypeScript - so you don't have to! Fixes and enhancements happily accepted.
JavaScript
28
star
3

WebLogImporter

A simple import of IIS Web Logs into a SQL Server Database so you can run fast queries against the information.
C#
17
star
4

astro-accelerator

An Astro-flavoured starting point.
JavaScript
11
star
5

JavaKatas

A home for my Java Katas.
Java
10
star
6

TfsCruiser

Build dashboard for TFS.
C#
8
star
7

SeleniumSuperDriver

A WebDriver that distributes commands to multiple drivers in parallel.
JavaScript
8
star
8

Katelyn

Well known for Crawling.
C#
6
star
9

JestSpec

Gherkin feature files for Jest.
JavaScript
5
star
10

jQuery-Plugins

All my jQuery Plugins in one handy place.
JavaScript
4
star
11

Hound

A C# library for publishing events and metrics to Datadog via the Datadog API.
C#
3
star
12

Cruiser

Cruise Control Information Radiator / Dashboard
HTML
3
star
13

MovieRentals

The starting point for the movie rentals mob programming exercise.
C#
3
star
14

SmtpStub

A simple SMTP server for testing that collects emails on a specified port and logs them to the file system.
C#
2
star
15

tsGuard

TypeScript Type Guard Library.
TypeScript
2
star
16

jquery-glider

A global slider plugin for jQuery, which support left-to-right and right-to-left languages.
HTML
2
star
17

astro-accelerator-utils

Utility classes for Astro Accelerator
JavaScript
2
star
18

BottlesOfBeer

C# Shameless Green for 99 Bottles of OOP
C#
2
star
19

RemoteAccessMonitor

Rescued from Codeplex!
HTML
2
star
20

TarnishedRose

Gilded rose exercise.
C#
1
star
21

wordpress-phonotonal

HTML
1
star
22

PICZ

Image tools for ASP.NET MVC Applications
PowerShell
1
star
23

PixelCounter

Analyses an image and scores different colour ranges.
TypeScript
1
star
24

TicTacToe

TicTacToe Kata
C#
1
star
25

stevefenton.co.uk

My personal site and blog
JavaScript
1
star
26

cookieglue

A working example of a re-usable framework for GDPR compliant cookie consent and script execution.
HTML
1
star
27

jekyll-boilerplate

My stripped out version of Jekyll
JavaScript
1
star
28

MultiQuery

A utility for issuing a query to multiple databases and aggregating the results.
C#
1
star
29

wordcrush

Crushes words to reduce the size of the English language for search purposes.
JavaScript
1
star