npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

nestjs-testing-utils

v1.0.5

Published

mock db and validators classes for nestjs

Readme

nestjs-testing-utils

A lightweight utility package for NestJS providing a generic mock in-memory repository and validation pipes to simplify both unit testing and production use.


Installation

npm install nestjs-testing-utils
# or
yarn add nestjs-testing-utils

What's Included

| Export | Description | |---|---| | BaseMockRepository<T> | Generic in-memory repository implementing IRepository<T> | | Validator<T> | NestJS pipe that validates a full request body against a reference object | | UpdateValidator<T> | NestJS pipe that validates partial update request bodies | | IRepository<T> | TypeScript interface for repository abstraction |


Usage

IRepository<T> — Repository Interface

Use this interface to type your repositories in services, keeping them decoupled from the underlying data source (TypeORM, mock, etc).

import { type IRepository } from 'nestjs-testing-utils';
import { Order } from './entities/order.entity';

@Injectable()
export class OrdersService {
  constructor(
    @Inject('OrderRepository')
    private readonly orderRepo: IRepository<Order>,
  ) {}
}

BaseMockRepository<T> — In-Memory Mock Repository

Extend BaseMockRepository to create a mock repository backed by an in-memory array. Useful for unit tests or in-memory/mock database modules.

import { BaseMockRepository } from 'nestjs-testing-utils';
import { Order } from './entities/order.entity';
import { mockOrders } from '../mockDatas/orders.stub';

export class OrderMockRepository extends BaseMockRepository<Order> {
  constructor() {
    super(Promise.resolve(mockOrders));
  }

  // Optionally override methods for custom behaviour
  async create(entity: Order): Promise<Order | null> {
    return super.create({ ...entity, time: new Date() });
  }
}

You can also implement IRepository<T> on your production TypeORM repository to keep the same interface:

import { IRepository } from 'nestjs-testing-utils';
import { Repository } from 'typeorm';

export class BaseTypeormRepository<T extends { id: string }>
  implements IRepository<T>
{
  constructor(protected readonly repo: Repository<T>) {}
  // ... implement methods
}

Using in NestJS Unit Tests

IRepository<T> makes it easy to mock repositories in @nestjs/testing:

import { IRepository } from 'nestjs-testing-utils';
import { Order } from './entities/order.entity';

describe('OrdersService', () => {
  let orderRepo: IRepository<Order>;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      providers: [
        OrdersService,
        {
          provide: 'OrderRepository',
          useValue: {
            create: jest.fn(),
            update: jest.fn(),
            findBy: jest.fn(),
            findOneBy: jest.fn(),
            deleteBy: jest.fn(),
            isExists: jest.fn(),
          },
        },
      ],
    }).compile();

    orderRepo = module.get<IRepository<Order>>('OrderRepository');
  });
});

Validator<T> — Full Body Validation Pipe

Validates that an incoming request body matches the full structure and types of a reference object. Throws BadRequestException if any field is missing or has the wrong type.

import { Validator } from 'nestjs-testing-utils';

const referenceOrder = { username: '', productId: '', quantity: 0 };

@Post()
create(@Body(new Validator(referenceOrder)) body: CreateOrderDto) {
  return this.ordersService.create(body);
}

UpdateValidator<T> — Partial Update Validation Pipe

Validates partial update bodies — only validates fields that are present in the request.

import { UpdateValidator } from 'nestjs-testing-utils';

const referenceOrder = { username: '', productId: '', quantity: 0 };

@Patch(':id')
update(@Body(new UpdateValidator(referenceOrder)) body: Partial<CreateOrderDto>) {
  return this.ordersService.update(body);
}

IRepository<T> Interface

export interface IRepository<T> {
  create(entity: Partial<T>): Promise<T | null>;
  findBy(where?: Partial<T>, isOr?: boolean): Promise<T[]>;
  isExists(where: Partial<T>, isOr?: boolean): Promise<boolean>;
  findOneBy(where: Partial<T>, isOr?: boolean): Promise<T | null>;
  update(entity: Partial<T> & { id: string }): Promise<T | null>;
  deleteBy(where: Partial<T>, isOr?: boolean): Promise<void>;
}

License

ISC