Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom TypeORM Repository undefined in NestJS integration tests #13095

Closed
4 of 15 tasks
JoaoP12 opened this issue Jan 24, 2024 · 6 comments
Closed
4 of 15 tasks

Custom TypeORM Repository undefined in NestJS integration tests #13095

JoaoP12 opened this issue Jan 24, 2024 · 6 comments
Labels
needs triage This issue has not been looked into

Comments

@JoaoP12
Copy link

JoaoP12 commented Jan 24, 2024

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

I'm trying to write integration tests for my Nest.js application, but something in the test context is making my custom TypeORM repositories undefined. This is probably happening because I'm not using @InjectRepository. Instead, I create request scoped injectables that extends a BaseRepository in order to manage the transactions in my requests. (I create and commit/rollback one transaction per request using interceptors. More about that in this article: https://medium.com/@dev.muhammet.ozen/advanced-transaction-management-with-nestjs-typeorm-43a839363491)

import { Test, TestingModule } from '@nestjs/testing';
import { TypeOrmModule } from '@nestjs/typeorm';
import { config } from 'dotenv';
import { ProductService } from '../src/product/product.service';
import { ProductRepository } from '../src/repositories/product.repository';

config();

describe('AppController (e2e)', () => {
  let productService: ProductService;
  let productRepo: ProductRepository;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        TypeOrmModule.forRoot({
          type: 'postgres',
          url: process.env.TEST_DB_URL,
          logging: false,
          entities: [__dirname + '/../src/entities/*.entity{.ts,.js}'],
        }),
      ],
      providers: [ProductService, ProductRepository],
    }).compile();

    productService = module.get<ProductService>(ProductService);
    productRepo = await module.resolve(ProductRepository);
  });

  it('should pass, but does not', async () => {
    const result = await productService.getProductByName('randomName');
    expect(result).toBeNull();
  });

  it('passes', async () => {
    const result = await productRepo
      .getRepository()
      .findOne({ where: { name: 'randomName' } });
    expect(result).toBeNull();
  });
});

When I run the tests, I get the following error:

TypeError: Cannot read properties of undefined (reading 'getRepository')

The productRepo inside ProductService.getProductByName is undefined. I've already tried changing the scope to default to verify whether that was the issue, but it wasn't.

I also wrote a test with the same logic as calling getProductByName, but using the repository directly. Strangely, it works.

Just by running the tests in the minimal repository I provided shall reproduce the error. When you run the application using yarn start or yarn start:dev, it works as expected.

Minimum reproduction code

https://github.com/JoaoP12/nest-typeorm-issue

Steps to reproduce

  1. yarn test:watch
  2. See the error

Expected behavior

I expected the tests to pass.

Package

  • I don't know. Or some 3rd-party package
  • @nestjs/common
  • @nestjs/core
  • @nestjs/microservices
  • @nestjs/platform-express
  • @nestjs/platform-fastify
  • @nestjs/platform-socket.io
  • @nestjs/platform-ws
  • @nestjs/testing
  • @nestjs/websockets
  • Other (see below)

Other package

@nestjs/typeorm

NestJS version

10.0.0

Packages versions

{
  "dependencies": {
    "@nestjs/common": "^10.0.0",
    "@nestjs/core": "^10.0.0",
    "@nestjs/platform-express": "^10.0.0",
    "@nestjs/typeorm": "^10.0.1",
    "dotenv": "^16.4.0",
    "pg": "^8.11.3",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^7.8.1",
    "typeorm": "^0.3.19"
  },
  "devDependencies": {
    "@nestjs/cli": "^10.0.0",
    "@nestjs/schematics": "^10.0.0",
    "@nestjs/testing": "^10.0.0",
    "@types/express": "^4.17.17",
    "@types/jest": "^29.5.2",
    "@types/node": "^20.3.1",
    "@types/supertest": "^6.0.0",
    "@typescript-eslint/eslint-plugin": "^6.0.0",
    "@typescript-eslint/parser": "^6.0.0",
    "eslint": "^8.42.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-prettier": "^5.0.0",
    "jest": "^29.5.0",
    "prettier": "^3.0.0",
    "source-map-support": "^0.5.21",
    "supertest": "^6.3.3",
    "ts-jest": "^29.1.0",
    "ts-loader": "^9.4.3",
    "ts-node": "^10.9.1",
    "tsconfig-paths": "^4.2.0",
    "typescript": "^5.1.3"
  }
}

Node.js version

18.17.1

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

Using Postgres 16.1

@JoaoP12 JoaoP12 added the needs triage This issue has not been looked into label Jan 24, 2024
@micalevisk
Copy link
Member

@JoaoP12
Copy link
Author

JoaoP12 commented Jan 24, 2024

have you tried this: https://docs.nestjs.com/fundamentals/testing#testing-request-scoped-instances ?

How would I apply that solution to my problem?
I even tried changing the scope of ProductRepository, but it turned out not to be the problem, apparently.

@micalevisk
Copy link
Member

micalevisk commented Jan 24, 2024

nvm

this is wrong:

productService = module.get<ProductService>(ProductService);

you must use module.resolve because of ProductService's scope (is not singleton because it depends on a request-scoped provider)

@micalevisk micalevisk closed this as not planned Won't fix, can't repro, duplicate, stale Jan 24, 2024
@JoaoP12
Copy link
Author

JoaoP12 commented Jan 24, 2024

Thank you for the answer, it worked :)

@stormGui
Copy link

How to solve it, I also encountered the same problem

@micalevisk
Copy link
Member

micalevisk commented Jan 25, 2024

@stormGui

How to solve it

#13095 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs triage This issue has not been looked into
Projects
None yet
Development

No branches or pull requests

3 participants