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 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-db-unit

v3.0.2

Published

Useful utils to simplify integration tests for nestjs / typeorm / postgres projects

Downloads

163

Readme

nestjs-db-unit

Test Coverage Status

This util is designed to simplify integration tests for nestjs/typeorm/postgres projects it replace postgres DB connection with sqlite in memory DB for test environment

Usage

Starting v3.0.0 the main usage for this library is changed, we do not need custom annotations any more and no need include into prod code. Since sqlite and postgres have different sets of data type and typeorm does not support easy way to redefine those types for test environment, so this lib patch typeorm annotations, wrappers for @Column, @CreateDateColumn, @UpdateDateColumn etc... annotations. There are some restriction:

  • you have to use commonjs modules for successful library patch: in tsconfig.json
...
{
    "compilerOptions": {
        "module": "commonjs",
     }
}
...
  • import nestjs-db-unit at very top of your tests (you have to patch typeorm first)
import { DbUnit } from 'nestjs-db-unit';
...

Example

import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';

@Entity({ name: 'users' })
export class User {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @Index('email')
  @Column({ unique: true})
  email!: string;

  @Column({type: 'json', nullable: true})
  meta!: object;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt!: Date;
}

This is example of service under test:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './entities/users';

@Injectable()
export class AppService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async getUser(id: string) {
    return this.userRepository.findOne(id);
  }
}

This is example of test:

import { DbUnit } from 'nestjs-db-unit'; //on top
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getRepository, Repository } from 'typeorm';
import { AppService } from './app.service';
import { User } from './entities/users';

const data = {
    User: [{
       id: 'test',
       email: '[email protected]' 
    }]
}
describe('AppController', () => {
  let service: AppService;
  let db = new DbUnit();
  let userRepo: Repository<User>;

  beforeEach(async () => {
    const conn = await db.initDb({ entities: [User] });
    userRepo = getRepository(User);
    const app: TestingModule = await Test.createTestingModule({
      controllers: [],
      providers: [
        {
          provide: getRepositoryToken(User, conn),
          useValue: userRepo,
        },
        AppService,
      ],
    }).compile();
    await db.load(data)

    service = app.get<AppService>(AppService);
  });
  afterEach(() => db.closeDb());
  afterAll(()=>db.exitDb()) //optional

  it('should get user"', async () => {
    const ID = 'test'
    const user = await service.getUser(ID);
    expect(user.email).toEqual('[email protected]');
  });
});

Installation

npm i nestjs-db-unit

API

DbUnit - utility class

import {DbUnit} from 'nestjs-db-unit'
  • constructor(options?: Options)

    options could be {debug:true} optional

    it used to add more logs from DB

  • DbUnit::initDb(config)

    config mandatory param, it should contain list of entities, e.g. {entities: [User]}

    it returns Promise resolved as DB connection

  • DbUnit::closeDb()

    initialize DB connection (clean sqlite in-memory DB)

  • DbUnit::exitDb()

    close DB connection (close sqlite in-memory DB)

  • DbUnit::load(data)

    it load data into DB

    data format must be like this:

    {
        <Entity1 name>:[
            <entity1_1 data>,
            <entity1_2 data>,
        ],
        <Entity2 name>:[
            <entity2_1 data>,
            <entity2_2 data>,
        ]
    }

    the data schema support relations, you can specify entity id and use it in followup entity data

You can find more examples for Integration and End to End tests at /test folder

License

MIT