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

typeorm-test-transactions

v3.6.1

Published

A transactional wrapper for tests that use TypeORM that automatically rolls back the transaction at the end of the test.

Downloads

7,456

Readme

TypeORM Test Transactions

NPM

oclif Version Downloads/week License Build Status

Have you wanted to run tests on a project that uses TypeORM directly on the database and in parallel? A lot of the time we can't do this because artefacts and data from other tests can affect the result of our current tests. What usually happens, in this case, is that our tests become quite complicated when database entities are involved because we need to track exact entities. Our count() and other aggregations must have where clauses so that we don't see results from other tests that have already completed.

This library introduces a way to wrap tests in a transaction and automatically roll back the commits when the test ends. By doing this, you are able to run multiple tests concurrently and their data will not be seen by others.

You may argue that we should mock out the entities and not use a database at all. This is a valid point, but sometimes we want to test database constraints and the effects they can have on application logic.

Credit

Before I start, I did not add much to get this to work. The major reason why this is possible is because of the work done by odavid in his typeorm-transactional-cls-hooked library. Thanks for the great work odavid!

Limitations

It has come to my attention that this library is not consistent if you use the TypeORM entity manager. So you'll want to use typeorm-transactional-cls-hooked to add the @Transactional decorator above function calls and those transactions will work correctly. What a colleague has found is that, when you use a TypeORM entity manager, they are independent of each other and data may still write to the database.

Testing

Currently, I have created a small test suite that tests that there is a rollback in the transaction wrapper. The goal is to test as many database versions as possible, currently I have:

  • MySQL 5.7
  • MySQL 8.0
  • MariaDB 10
  • Postgres 9
  • Postgres 10
  • Postgres 11
  • Postgres 12
  • Postgres 13

The test badge represents tests that run over these databases: Build Status

Getting Started

In order to use this project you need to install the package,

npm install --save typeorm-test-transactions

# Not removing from the typeorm-transactional-cls-hooked
# dependency separation. If you don't have the below
# libraries then you'll need to install them as well
# See https://github.com/odavid/typeorm-transactional-cls-hooked

npm install --save typeorm reflect-metadata

When running your tests (I'm using jest and nestjs as the example), you'll want to wrap your test functions in the runInTransaction function.

import {
    runInTransaction,
    initialiseTestTransactions,
} from 'typeorm-test-transactions';
import { DatabaseModule } from '@modules/database/database.module';
import { Test } from '@nestjs/testing';

initialiseTestTransactions();

describe('Feature1Test', () => {
    beforeEach(async () => {
        const module = await Test.createTestingModule({
            imports: [DatabaseModule],
        }).compile();
    });

    describe('creation of 2 users', () => {
        it(
            'should allow me to create multiple users if the email address is different but name is the same',
            runInTransaction(async () => {
                await User.create({
                    email: '[email protected]',
                    name: 'Name',
                }).save();

                await User.create({
                    email: '[email protected]',
                    name: 'Name',
                }).save();

                expect(await User.count()).toEqual(2);
            }),
        );
    });

    describe('creation of one of the users in previous step', () => {
        it(
            'should allow me to create a user that is the same as the one in the previous step',
            runInTransaction(async () => {
                await User.create({
                    email: '[email protected]',
                    name: 'Name',
                }).save();

                expect(await User.count()).toEqual(1);
            }),
        );
    });
});

IMPORTANT! The example above wraps the entire test in a transaction and returns a function that jest executes. If you'd like to wrap parts of a test in a transaction, you need to call the function and await the result:

import {
    runInTransaction,
    initialiseTestTransactions,
} from 'typeorm-test-transactions';
import { DatabaseModule } from '@modules/database/database.module';
import { Test } from '@nestjs/testing';

initialiseTestTransactions();

describe('Feature1Test', () => {
    beforeEach(async () => {
        const module = await Test.createTestingModule({
            imports: [DatabaseModule],
        }).compile();
    });

    describe('creation of the same user in different sequential transactions', () => {
        it(
            'allows me to create the same user twice if they were each in a transaction',
            async () => {
                await runInTransaction(async () => {
                    await User.create({
                        email: '[email protected]',
                        name: 'Name',
                    }).save();

                    expect(await User.count()).toEqual(1);
                })();
                await runInTransaction(async () => {
                    await User.create({
                        email: '[email protected]',
                        name: 'Name',
                    }).save();

                    expect(await User.count()).toEqual(1);
                })();
            }
        );
    });
});

Troubleshooting

  • There are some cases when the transactions don't roll back. So far, I've found the reason for that to be that the typeorm connection was started before this package was initialised.
  • I have seen an issue opened typeorm-transactional-cls-hooked initialization #30 where there may be a problem around where you perform the initialisation. Once I get feedback, I'll update the documentation here.