# Testing Guards & Interceptors {#testing-guards--interceptors}


Test NestJS guards, interceptors, and middleware.


## Testing Guards {#testing-guards}


```typescript
import { ExecutionContext } from "@nestjs/common";
import { TenantPermissionGuard } from "./tenant-permission.guard";

describe("TenantPermissionGuard", () => {
  let guard: TenantPermissionGuard;

  beforeEach(() => {
    guard = new TenantPermissionGuard(mockReflector, mockEmployeeService);
  });

  it("should allow access for valid tenant", async () => {
    const context = createMockContext({
      user: { tenantId: "tenant-1", role: { name: "ADMIN" } },
    });

    const result = await guard.canActivate(context);
    expect(result).toBe(true);
  });

  it("should deny access for missing tenant", async () => {
    const context = createMockContext({
      user: { tenantId: null },
    });

    await expect(guard.canActivate(context)).rejects.toThrow();
  });
});

function createMockContext(overrides: any): ExecutionContext {
  return {
    switchToHttp: () => ({
      getRequest: () => ({
        user: overrides.user,
        headers: {},
        ...overrides,
      }),
    }),
    getHandler: () => ({}),
    getClass: () => ({}),
  } as unknown as ExecutionContext;
}
```


## Testing Interceptors {#testing-interceptors}


```typescript
describe("TransformInterceptor", () => {
  let interceptor: TransformInterceptor;

  beforeEach(() => {
    interceptor = new TransformInterceptor();
  });

  it("should wrap response in data object", async () => {
    const context = createMockContext({});
    const handler = {
      handle: () => of({ id: "1", name: "Test" }),
    };

    const result = await lastValueFrom(interceptor.intercept(context, handler));
    expect(result).toEqual({ data: { id: "1", name: "Test" } });
  });
});
```


## Testing Pipes {#testing-pipes}


```typescript
describe("UUIDValidationPipe", () => {
  const pipe = new UUIDValidationPipe();

  it("should pass valid UUID", () => {
    const uuid = "550e8400-e29b-41d4-a716-446655440000";
    expect(pipe.transform(uuid)).toBe(uuid);
  });

  it("should reject invalid UUID", () => {
    expect(() => pipe.transform("not-a-uuid")).toThrow(BadRequestException);
  });
});
```


## Related Pages {#related-pages}


- [Unit Testing Guide](https://sourcey-gauzy.pages.dev/testing/unit-testing/index.md) — unit tests
- [Guard System](https://sourcey-gauzy.pages.dev/architecture/guard-system/index.md) — guard architecture
- [Interceptor Patterns](https://sourcey-gauzy.pages.dev/architecture/interceptor-patterns/index.md) — interceptors
