nestjsx / crud

NestJs CRUD for RESTful APIs
https://github.com/nestjsx/crud/wiki
MIT License
4.09k stars 541 forks source link

TypeError: Cannot read property 'metadata' of undefined on test run #570

Open viru-rishu opened 4 years ago

viru-rishu commented 4 years ago

While running tests in my project, I am getting this error

TypeError: Cannot read property 'metadata' of undefined

Service file organisation.service.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { OrganisationService } from './organisation.service';
import { TypeOrmCrudService } from '@nestjsx/crud-typeorm';
import { Organisation } from './model/organisation.entity';
import { Repository } from 'typeorm';
import { getRepositoryToken } from '@nestjs/typeorm';
import { MockRepository } from '../shared/repo/mockrepository';

describe('OrganisationService', () => {
  let service: OrganisationService;
  let orgRepo: Repository;
  const mockrepository = new MockRepository();

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        OrganisationService,
        TypeOrmCrudService,
        {
          // how you provide the injection token in a test instance
          provide: getRepositoryToken(Organisation),
          // as a class value, Repository needs no generics
          useValue: mockrepository,
        },
      ],
    }).compile();

    service = module.get(OrganisationService);
    orgRepo = module.get>(getRepositoryToken(Organisation));
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});

mockrepository file : mockrepository.ts

export class MockRepository {
  public createQueryBuilder = jest.fn(() => this.queryBuilder);
  public manager = { transaction: a => Promise.resolve(a()) };
  public metadata = { connection: { options: { type: null } }, columns: [], relations: [] };
  public save = jest.fn();
  public delete = jest.fn();
  public update = jest.fn();
  public findOne = jest.fn();
  public findOneOrFail = jest.fn();
  public find = jest.fn();
  public getMany = jest.fn();
  public queryBuilder = {
      offset: jest.fn().mockReturnThis(),
      take: jest.fn().mockReturnThis(),
      orderBy: jest.fn().mockReturnThis(),
      skip: jest.fn().mockReturnThis(),
      limit: jest.fn().mockReturnThis(),
      from: jest.fn().mockReturnThis(),
      addFrom: jest.fn().mockReturnThis(),
      where: jest.fn().mockReturnThis(),
      andWhere: jest.fn().mockReturnThis(),
      innerJoinAndSelect: jest.fn().mockReturnThis(),
      leftJoinAndSelect: jest.fn().mockReturnThis(),
      getManyAndCount: jest.fn(),
      getMany: jest.fn(),
      getOne: jest.fn(),
      delete: jest.fn().mockReturnThis(),
      execute: jest.fn().mockReturnThis(),
  };
}

Also, I am getting this error TypeError: Cannot read property 'connection' of undefined in users.controller.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { UsersController } from './users.controller';
import { UsersService } from '../users/users.service';
import { User } from '../users/entities/users.entity';
import { UserOrgs } from './entities/user-org.entity';
import { Repository } from 'typeorm';
import { getRepositoryToken } from '@nestjs/typeorm';
import { TypeOrmModule } from '@nestjs/typeorm';
import { configService } from '../library/config/config.service';

describe('Users Controller', () => {
  let controller: UsersController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        TypeOrmModule.forRoot(configService.getTypeOrmConfig()),
      ],  
      controllers: [UsersController],
      providers:[
        UsersService,
        {
          // how you provide the injection token in a test instance
          provide: getRepositoryToken(User),
          // as a class value, Repository needs no generics
          useClass: Repository,
        },
        {
          // how you provide the injection token in a test instance
          provide: getRepositoryToken(UserOrgs),
          // as a class value, Repository needs no generics
          useClass: Repository,
        }
      ]
    }).compile();

    controller = module.get(UsersController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });
});

Would you please let me know where I am doing wrong.

Node Version : v10.16.2 Crud Version "@nestjsx/crud": "^4.6.2", "@nestjsx/crud-request": "^4.4.2", "@nestjsx/crud-typeorm": "^4.6.2",

wagnercsfilho commented 4 years ago

You don't need to import the TypeOrmCrudService class. Also use useClass instead of useValue.

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        ContractService,
        { provide: getRepositoryToken(Contract), useClass: MockRepository },
      ],
    }).compile();

    service = module.get<ContractService>(ContractService);
    repository = module.get(getRepositoryToken(Contract));
  });