Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a decorater usage in typescript?

Suppose there is a property decorator and a class uses that decorator on its certain properties.

function foo(options?: any) {
    return function (target: any, prop: string) {
        // some magic
    }
}

class Bar {
    @foo({ opt1: true }) zoo = 123
}

Suppose that I have covered foo's logic in my unit tests and now am willing to write a test ensures that

Bar class has used foo decorator on its property zoo with option { opt1: true }

How this test should be written ?

P.S. I'm using jest along with ts-jest and open to any other test frameworks if neccessary.

like image 270
Nandin Borjigin Avatar asked Oct 11 '18 04:10

Nandin Borjigin


People also ask

How do you use a decorator in TypeScript?

In TypeScript, you can create decorators using the special syntax @expression , where expression is a function that will be called automatically during runtime with details about the target of the decorator. The target of a decorator depends on where you add them.

How do you test for TypeScript?

For TypeScript, unit tests are run against the generated JavaScript code. In most TypeScript scenarios, you can debug a unit test by setting a breakpoint in TypeScript code, right-clicking a test in Test Explorer, and choosing Debug.

Are decorators still experimental in TypeScript?

As of writing this guide, decorators are still an experimental feature in TypeScript. To enable this feature, set the experimentalDecorators compiler flag either on the command line or in your tsconfig. json file.

How many decorators can be applied to a declaration in TypeScript?

It is applied to a property descriptor for the method. It can be used to observe, modify, or replace a method definition. We cannot use method decorator in a declaration file. The expression for the method decorator function accepts three arguments.


1 Answers

This is an interesting question.

Decorators are meant to be used directly thus cannot be mocked by normal means. This might be a legit case to use jest bypass mock.

However, IMO, the objective of your test is misplaced. You should not test the fact that it has been called with { opt1: true }, you should test the behavior of using such decorator, if possible.

Testing it has been called with { opt1: true } is the same as you want to test your findLCD(a: number, b: number) to make sure it has called Math.abs(a).

You should focus on the behavior (that findLCD(a, b) give you the correct result), instead of how the code does it.

The means, if your decorator @foo does something that is measurable, test against that instead.

For example, if @foo write some log entry, find a way to test the log entry is written, instead of @foo has been called in certain way.

like image 118
unional Avatar answered Oct 23 '22 09:10

unional