How to Write UnitTest on TypeOrm DataSource

Viewed 17

I want to write a unit test on typeorm Datasource but couldn't figure out a way to do it because I'm a newbie to unit testing. I already have spy on the entity. but I had to use the data for some custom queries, here is my code.

company.entity.ts

export class CompanyEntity {
  @PrimaryGeneratedColumn('uuid', {
    name: 'company_id',
  })
  id: string;

  @ManyToOne(() => StoreEntity, (store) => store.storeId, {
    onDelete: 'SET NULL',
  })
  @JoinColumn({ name: 'store_id', referencedColumnName: 'storeId' })
  store: StoreEntity;

  @Column({
    name: 'owner_name',
    type: 'varchar',
  })
  ownername: string;
}

comapany.service.ts

@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(CompanyEntity)
    private _companyRepository: Repository<CompanyEntity>,
    @InjectRepository(StoreEntity)
    private _storeEntityRepository: Repository<StoreEntity>,
    private readonly dataSource: DataSource,
  ) {}

  async findAll(offset = 0, size = 50) {
    try {
      return await this.dataSource
        .getRepository('company')
        .createQueryBuilder('company')
        .leftJoinAndSelect('company.store', 'store')
        .select([
          'company.company_id AS id',
          'company.owner_name AS ownername',
          'store.name AS store',
        ])
        .skip(offset)
        .take(size)
        .execute();
    } catch (error) {
      throw new Error(error);
    }
  }
}

service.spec.ts

describe('UsersService', () => {
  let service: CompanyService;
  let repository: Repository<CompanyEntity | CompanyEntity[]>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CompanyService,
        {
          provide: getRepositoryToken(CompanyEntity),
          useClass: Repository,
        },
      ],
    }).compile();

    service = module.get<CompanyService>(CompanyService);
    repository = module.get<Repository<CompanyEntity | CompanyEntity[]>>(
      getRepositoryToken(CompanyEntity),
    );
  });

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

  it('find all should return array company objects', async () => {
    ---------- wants to write the data source test here ----------
  });
});
0 Answers
Related