DEV Community

Cover image for Writing Typescript unit tests with ArchiTest
Ralaivao Andry
Ralaivao Andry

Posted on • Updated on

Writing Typescript unit tests with ArchiTest

Have you ever wrote unit tests for your code and struggled on the "what" to test in your code?
Have you ever wondered why you have to learn new terms and concepts to write tests?
Have you ever thought that writing tests should not be that hard and counterintuitive?

If you responded positively to one of those, your have to try "ArchiTest", a new way to write test.

What is it?

ArchiTest is an set of principles that breaks down the testing practices as we know it. It's objective is to use Object Oriented Programing basic principles to:

  • Ease the tests writing
  • To improve your coding skills

It is mainly based on four principles:

  • "No new terms": you don't have to learn vocabularies like "describe", "it", "expect", "mock", .... Let's use already available terms in our programming language
  • "Class and method as unit of test": Let's use OOP correctly and test behaviors of our classes and objects, not some procedures or functions.
  • "Inheritance as mocking system": Let's use inheritance to override dependencies or external coupling of our code
  • "Test transparency": Let's not worry about, side-effects and complex test expectations (notNull, isTruthy, isNotEqual, haveProperty, and other shenanigans). Your code will be better!

Implementation

For now, a Typescript implementation of those principles is available. We are working on bringing more languages supports in the future. Your help is very welcome

Quickly try it

Take a look and try ArchiTest for Typescript. I promise it will take you less than five minutes.

Install

In your typescript project, install the package

npm install -D @archikoder/architest
Enter fullscreen mode Exit fullscreen mode

Configure

In your package.json file, add a script to launch your test with the command "architest"

   "scripts": {
       "test": "architest",
       ...
   }
Enter fullscreen mode Exit fullscreen mode

Test

Choose a class to test. For example, if you have a class like this:

export class User{
    private firstname: string;
    private lastname: string;

    constructor(firstname: string, lastname: string){
        this.firstname = firstname;
        this.lastname = lastname;
    }

    public printName(): string{
        return firstname + " " + lastname;
    }
}
Enter fullscreen mode Exit fullscreen mode

In the same file, import the test decorator and you can write your test class like this:

import { test } from "@archikoder/architest"; 
...
export class WilliamShakespeare extends User{
    constructor(){
        super("William", "Shakespeare");
    }

    @test 
    public printName(): string{
         return "William Shakespeare";
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the test

npm run test
Enter fullscreen mode Exit fullscreen mode

See the magic happen!

Top comments (0)