Rjk Rjk - 1 year ago 159
TypeScript Question

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", ()=> {
let baseURL:string;

expect(baseURL typeOf string).toBe(true)

Answer Source

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');