Testing TypeScript Decorators: Class, Method, and Property Decorators
TypeScript decorators add behavior invisibly — which makes them powerful and easy to forget to test. This post covers strategies for testing class decorators, method decorators, property decorators, parameter decorators, and NestJS-style metadata-based patterns.
Key Takeaways
Test the decorator's effect, not its internals. A method decorator that adds logging should be tested by verifying logs appear, not by inspecting the decorator function directly.
Metadata reflection requires reflect-metadata in your test setup. Without import 'reflect-metadata' before your tests, Reflect.getMetadata returns undefined — and your NestJS-style tests silently pass for the wrong reasons.
Class decorators can be tested without a DI container. Even NestJS decorators like @Injectable() just write metadata — you can verify that metadata without spinning up a full NestJS application.
Property decorators are the trickiest. They fire once when the class is defined, not when properties are accessed, so you need to instantiate the class and exercise the decorated property to verify behavior.
Legacy decorators and the new TC39 decorators have different APIs. TypeScript 5.0+ supports both — know which you're targeting before you write tests.
Decorators are one of TypeScript's most powerful features and one of the least-tested. They're invisible at the call site — you sprinkle @Injectable() or @Validate() on a class and trust that something happens. This post makes that trust explicit by showing you how to verify decorator behavior at every level.
TypeScript Decorator Basics and tsconfig
Before testing, confirm your tsconfig enables decorators correctly:
{
"compilerOptions": {
"experimentalDecorators": true, // required for legacy decorators
"emitDecoratorMetadata": true, // required for reflect-metadata
"target": "ES2017" // decorators need a compatible target
}
}For emitDecoratorMetadata to work, you also need to install and import reflect-metadata:
npm install reflect-metadataIn your test setup file:
// jest.setup.ts (referenced in jest.config.ts setupFilesAfterFramework)
import 'reflect-metadata';Without this, any Reflect.getMetadata call returns undefined, and decorator-dependent code silently misbehaves.
Testing Class Decorators
A class decorator is applied to the constructor. It can replace, modify, or wrap the class:
function Singleton<T extends { new(...args: any[]): {} }>(constructor: T) {
let instance: InstanceType<T>;
return class extends constructor {
constructor(...args: any[]) {
super(...args);
if (instance) return instance;
instance = this as any;
}
} as unknown as T;
}
@Singleton
class DatabaseConnection {
id = Math.random();
connect() { return 'connected'; }
}Test the observable behavior:
describe('@Singleton', () => {
beforeEach(() => {
// Reset the singleton between tests — this is the tricky part
// You need a way to reset state, or use a factory pattern in tests
});
it('returns the same instance on multiple constructions', () => {
const a = new DatabaseConnection();
const b = new DatabaseConnection();
expect(a).toBe(b);
expect(a.id).toBe(b.id);
});
it('preserves the class interface', () => {
const conn = new DatabaseConnection();
expect(conn.connect()).toBe('connected');
});
it('is an instance of the original class', () => {
const conn = new DatabaseConnection();
expect(conn).toBeInstanceOf(DatabaseConnection);
});
});The hardest part of testing class decorators is state reset. If your decorator stores state in a closure (like the singleton instance above), you need a way to reset it between tests. Options:
- Export a
reset()function for testing - Use a factory approach where the decorator reads from an external registry you can clear
- Use Jest's module registry reset:
jest.resetModules()and re-import
Testing Method Decorators
Method decorators are the most common and usually the easiest to test:
function Log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with`, args);
const result = original.apply(this, args);
console.log(`${propertyKey} returned`, result);
return result;
};
return descriptor;
}
class Calculator {
@Log
add(a: number, b: number): number {
return a + b;
}
}Test by verifying the decorator's side effects:
describe('@Log decorator', () => {
let calculator: Calculator;
let consoleSpy: jest.SpyInstance;
beforeEach(() => {
calculator = new Calculator();
consoleSpy = jest.spyOn(console, 'log').mockImplementation();
});
afterEach(() => {
consoleSpy.mockRestore();
});
it('logs the method call with arguments', () => {
calculator.add(2, 3);
expect(consoleSpy).toHaveBeenCalledWith('Calling add with', [2, 3]);
});
it('logs the return value', () => {
calculator.add(2, 3);
expect(consoleSpy).toHaveBeenCalledWith('add returned', 5);
});
it('does not affect the return value', () => {
const result = calculator.add(2, 3);
expect(result).toBe(5);
});
it('logs on every call, not just the first', () => {
calculator.add(1, 2);
calculator.add(3, 4);
expect(consoleSpy).toHaveBeenCalledTimes(4); // 2 logs per call
});
});For async method decorators:
function Retry(times: number) {
return function(target: any, key: string, descriptor: PropertyDescriptor) {
const original = descriptor.value;
descriptor.value = async function(...args: any[]) {
let lastError: Error;
for (let i = 0; i <= times; i++) {
try {
return await original.apply(this, args);
} catch (e) {
lastError = e as Error;
if (i === times) throw lastError;
}
}
};
};
}
class ApiClient {
@Retry(3)
async fetchData(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error('Request failed');
return response.text();
}
}describe('@Retry(3) decorator', () => {
it('retries failed requests up to 3 times', async () => {
const client = new ApiClient();
const mockFetch = jest.fn()
.mockRejectedValueOnce(new Error('fail'))
.mockRejectedValueOnce(new Error('fail'))
.mockResolvedValueOnce({ ok: true, text: () => 'success' });
global.fetch = mockFetch;
const result = await client.fetchData('https://api.example.com/data');
expect(result).toBe('success');
expect(mockFetch).toHaveBeenCalledTimes(3);
});
it('throws after exhausting all retries', async () => {
const client = new ApiClient();
global.fetch = jest.fn().mockRejectedValue(new Error('always fails'));
await expect(client.fetchData('https://api.example.com/data'))
.rejects.toThrow('always fails');
expect(global.fetch).toHaveBeenCalledTimes(4); // 1 initial + 3 retries
});
});Testing Property Decorators
Property decorators are trickier because they fire at class definition time, not at property access time:
function Required(target: any, propertyKey: string) {
let value: any;
Object.defineProperty(target, propertyKey, {
get() { return value; },
set(newValue) {
if (newValue === null || newValue === undefined) {
throw new Error(`${propertyKey} is required and cannot be null or undefined`);
}
value = newValue;
},
enumerable: true,
configurable: true,
});
}
class UserDto {
@Required
name!: string;
@Required
email!: string;
age?: number;
}describe('@Required decorator', () => {
it('allows setting a valid value', () => {
const user = new UserDto();
user.name = 'Alice';
expect(user.name).toBe('Alice');
});
it('throws when setting null', () => {
const user = new UserDto();
expect(() => { user.name = null as any; })
.toThrow('name is required and cannot be null or undefined');
});
it('throws when setting undefined', () => {
const user = new UserDto();
expect(() => { user.name = undefined as any; })
.toThrow('name is required');
});
it('does not affect optional properties', () => {
const user = new UserDto();
user.age = undefined; // Should not throw
expect(user.age).toBeUndefined();
});
});Testing Metadata-Based Decorators
The most powerful decorator patterns use Reflect.metadata to store metadata on classes and methods, then read it at runtime for validation, DI, routing, etc.:
const ROLES_KEY = 'roles';
function Roles(...roles: string[]) {
return Reflect.metadata(ROLES_KEY, roles);
}
function getRoles(target: any, key?: string): string[] {
if (key) {
return Reflect.getMetadata(ROLES_KEY, target, key) ?? [];
}
return Reflect.getMetadata(ROLES_KEY, target) ?? [];
}
class UserController {
@Roles('admin', 'superuser')
deleteUser(id: string) { /* ... */ }
@Roles('user', 'admin')
getProfile(id: string) { /* ... */ }
listUsers() { /* no roles required */ }
}Test the metadata directly:
describe('@Roles decorator', () => {
it('stores roles metadata on methods', () => {
const roles = getRoles(UserController.prototype, 'deleteUser');
expect(roles).toEqual(['admin', 'superuser']);
});
it('stores different roles for different methods', () => {
const deleteRoles = getRoles(UserController.prototype, 'deleteUser');
const profileRoles = getRoles(UserController.prototype, 'getProfile');
expect(deleteRoles).toContain('admin');
expect(deleteRoles).not.toContain('user');
expect(profileRoles).toContain('user');
expect(profileRoles).not.toContain('superuser');
});
it('returns empty array for methods without @Roles', () => {
const roles = getRoles(UserController.prototype, 'listUsers');
expect(roles).toEqual([]);
});
});Testing Parameter Decorators
Parameter decorators are used heavily in DI frameworks. They store metadata about constructor or method parameters:
function Inject(token: string) {
return function(target: any, propertyKey: string | undefined, parameterIndex: number) {
const existing = Reflect.getMetadata('inject:tokens', target) ?? {};
existing[parameterIndex] = token;
Reflect.defineMetadata('inject:tokens', existing, target);
};
}
class ServiceA {
constructor(
@Inject('DATABASE') private db: any,
@Inject('LOGGER') private logger: any
) {}
}describe('@Inject parameter decorator', () => {
it('stores injection tokens by parameter index', () => {
const tokens = Reflect.getMetadata('inject:tokens', ServiceA);
expect(tokens).toEqual({ 0: 'DATABASE', 1: 'LOGGER' });
});
it('preserves the original constructor behavior', () => {
const mockDb = { query: jest.fn() };
const mockLogger = { log: jest.fn() };
const service = new ServiceA(mockDb, mockLogger);
// Service was constructed successfully with injected values
expect(service).toBeInstanceOf(ServiceA);
});
});Testing NestJS-Style Decorators
NestJS decorators are metadata decorators with a framework interpreter. You can test the metadata they store without running the full NestJS application:
import { Controller, Get, Injectable, Module } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
@Controller('users')
class UsersController {
@Get(':id')
findOne() {}
}import { Reflector } from '@nestjs/core';
import { PATH_METADATA, METHOD_METADATA } from '@nestjs/common/constants';
import { RequestMethod } from '@nestjs/common';
describe('NestJS decorator metadata', () => {
it('sets controller path metadata', () => {
const path = Reflect.getMetadata(PATH_METADATA, UsersController);
expect(path).toBe('users');
});
it('sets route method metadata', () => {
const method = Reflect.getMetadata(METHOD_METADATA, UsersController.prototype.findOne);
expect(method).toBe(RequestMethod.GET);
});
it('sets route path metadata', () => {
const path = Reflect.getMetadata(PATH_METADATA, UsersController.prototype.findOne);
expect(path).toBe(':id');
});
});For testing the full integration of a NestJS module (DI resolution, guards, interceptors), use @nestjs/testing:
import { Test, TestingModule } from '@nestjs/testing';
describe('UsersController integration', () => {
let controller: UsersController;
let service: UsersService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [
{
provide: UsersService,
useValue: { findOne: jest.fn() },
},
],
}).compile();
controller = module.get<UsersController>(UsersController);
service = module.get<UsersService>(UsersService);
});
it('calls service.findOne with the correct id', async () => {
const mockUser = { id: '1', name: 'Alice' };
jest.spyOn(service, 'findOne').mockResolvedValue(mockUser);
const result = await controller.findOne('1');
expect(service.findOne).toHaveBeenCalledWith('1');
expect(result).toEqual(mockUser);
});
});Testing Decorator Composition
When decorators are composed (multiple decorators on one target), test the composition:
@Log
@Authenticate
@RateLimit(100)
class ApiEndpoint {
handle(req: Request): Response { /* ... */ }
}Decorators apply bottom-up: @RateLimit first, then @Authenticate, then @Log. Test that the composition behaves correctly when multiple decorators interact:
describe('composed decorators', () => {
it('applies rate limiting before authentication', () => {
// Rate limiter should reject before auth is checked when limit exceeded
});
it('logs even when authentication fails', () => {
// @Log wraps the whole thing, so it should log auth failures too
});
});End-to-End Validation
When decorator-heavy code is in production, end-to-end tests with tools like HelpMeTest verify that the decorator-driven behavior (authorization checks, rate limiting, validation) actually works in the full request path — not just in the unit tests that check the metadata. Decorator unit tests verify the wiring; E2E tests verify the behavior.
Decorator testing requires discipline because the behavior is indirect. The @Required decorator doesn't look like code that runs — until a null value throws an error at runtime and you realize it does. Write the tests first, write the decorator to make them pass, and you'll have decorators you can actually trust.