typeorm-transactional icon indicating copy to clipboard operation
typeorm-transactional copied to clipboard

Error when running E2E tests with Nest.js

Open no-creative-name opened this issue 2 years ago • 4 comments

Hi there,

thanks for the package! It really is super useful. My issue is that we can't run our E2E tests with it as of now. We get the console error Error: DataSource with name "default" has already added. all the time. I assume it has to do with the dataSourceFactory being called multiple times (in multiple TestingModules) for the same database. Any suggestion how to approach/debug this? The setup is more or less the same as the default testing setup that Nest.js suggests.

Screenshot 2022-09-28 at 16 32 31

no-creative-name avatar Sep 28 '22 14:09 no-creative-name

Hi, thanks for your issue. I think I need to investigate this more to handle this.

Now you can also use something like that to prevent adding the data source several times:

import { addTransactionalDataSource, getDataSourceByName } from 'typeorm-transactional';

// ...

TypeOrmModule.forRootAsync({
    dataSourceFactory: async (options) => {
      return getDataSourceByName('default') || addTransactionalDataSource(new DataSource(options));
    },
  });

or

import { addTransactionalDataSource, deleteDataSourceByName } from 'typeorm-transactional';

// ...

TypeOrmModule.forRootAsync({
    dataSourceFactory: async (options) => {
      deleteDataSourceByName('default');

      return addTransactionalDataSource(new DataSource(options));
    },
  });

Aliheym avatar Sep 28 '22 14:09 Aliheym

If I use the getDataSourceByName workaround, then I get the error Error: No CLS namespace defined in your app ... please call initializeTransactionalContext() before application start. when running the tests. Even though I actually call initializeTransactionalContext() in the beginning of my bootstrap() function. It seems like something's off at a deeper level here.

Edit: My bad, I forgot that bootstrap() wasn't called by the E2E test setup. When I call initializeTransactionalContext() in my E2E setup function it works. Thanks a bunch! If you need testing or anything else for the main issue to solve here, let me know.

no-creative-name avatar Sep 29 '22 06:09 no-creative-name

Thanks! Will notify you.

Aliheym avatar Sep 29 '22 09:09 Aliheym

      return getDataSourceByName('default') || addTransactionalDataSource(new DataSource(options));

Thank you. If I'm not mistaken if we add a name to options, if we use multiple data sources, all the data sources get the name as the default

dsmabulage avatar Feb 06 '24 04:02 dsmabulage