简体   繁体   中英

Unit testing Typescript decorators

I have an application built on typescript with decorators for some convenience property assignments and wondering how I can go about writing unit tests for them.

 export function APIUrl() {
        return function (target: any, key: string) {
             let _value = target[key];

          function getter() {
            return _value;
          }

          function setter(newValue) {
            _value = getApiURL();
          }

          if (delete target[key]) {
            Object.defineProperty(target, key, {
                get: getter,
                set: setter
            });
          }
        };
    }

In a spec class I have,

 it("should return url string", ()=> {
   @APIUrl();
   let baseURL:string;

   expect(baseURL typeOf string).toBe(true)
 })

Since decorators are just functions I would suggest to just test them like any other function. And only if you really need to, add one tests that shows how to use the decorator with a class/member/...

Here is an example such a test could look like:

import test from 'ava';
import { APIUrl } from './path';

const decorate = new APIUrl();

test.before(t => {
  let obj = { someProp: 'foo' };
  decorate(obj, 'someProp');
  t.context.foo = obj;
});

test('should return original value', t => {
  t.is(t.context.foo.someProp, 'foo');
});

Another approach could be to setup some properties and/or methods that use your decorators and test their usage directly.

Note: decorators can only be used on class methods and members so you'd need to create a dummy class in your test.

Here's an example:

//Test Setup
class Test {

    @APIUrl()
    url: string;

    @AnotherDecorator()
    anotherFunction() {}

}


//Unit tests
describe('Decorator Tests', () => {
    it('should work', () => {
       const t = new Test();
       expect(t.url).toEqual("something");
       expect(t.anotherFunction()).toReturn("something else");
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM