Please make sure that the argument CrawlsRepositoryat index [0] is available in the RootTestModule context

128 Views Asked by At

I'm trying to test a class via Nest. In this class (cf image below), the person who coded the class, create a repository via typeorm.

service code

import { Injectable, BadRequestException } from '@nestjs/common';
import { CreateCrawlDto } from './dto/create-crawl.dto';
import { UpdateCrawlDto } from './dto/update-crawl.dto';
import { CrawlProgress } from './entities/crawlProgress.entity';
import { CrawlRequest } from './entities/crawlRequest.entity';
import { CrawlsRepository } from './crawls.repository';
import { CreateCustomerDto } from './dto/create-crawl-customer.dto';

@Injectable()
export class CrawlsService {
  constructor(
    private crawlRepository: CrawlsRepository
  ) { }

  async insertRequest(createCrawlDto: CreateCrawlDto) {
    return await this.crawlRepository.insertRequest(createCrawlDto);
  }

  async findRequest(): Promise<CrawlRequest[]> {
    return await this.crawlRepository.findRequest();
  }

  async findProgress(): Promise<CrawlProgress[]> {
    return await this.crawlRepository.findProgress();

  }

  async findProgressCustomerCount(id: number) {
    return await this.crawlRepository.findProgressCustomerCount(id);
  }

  async findProgressCustomer(id: number) {
    return await this.crawlRepository.findProgressCustomer(id);
  }

  async update(id: string, updateCrawlDto: UpdateCrawlDto) {
    const temp_data = await this.crawlRepository.update(id, updateCrawlDto);
    if (temp_data.affected === 0) {
      throw new BadRequestException('Not Found Request Data', { cause: new Error(), description: 'Not Found Request Data' })
    }
    return temp_data
  }

  async remove(id: string) {
    return await this.crawlRepository.remove(id);
  }
  async insertCustomer(createCustomer: CreateCustomerDto) {
    return await this.crawlRepository.insertCustomer(createCustomer);
  }
  async findCustomertotal() {
    return await this.crawlRepository.findCustomerTotal();
  }
}

repository code

import { Injectable, Inject } from "@nestjs/common";
import { CrawlRequest } from "./entities/crawlRequest.entity";
import { CrawlProgress } from "./entities/crawlProgress.entity";
import { CreateCrawlDto } from "./dto/create-crawl.dto";
import { UpdateCrawlDto } from "./dto/update-crawl.dto";
import { CrawlCustomer } from "./entities/crawlCustomer.entity";
import { CreateCustomerDto } from "./dto/create-crawl-customer.dto";
import { Repository } from 'typeorm';

@Injectable()
export class CrawlsRepository {
  constructor(
    @Inject('CRAWL_REPOSITORY')
    private crawlRepo: Repository<CrawlRequest>,
    @Inject('CRAWL_PROGRESS_REPOSITORY')
    private crawlProg: Repository<CrawlProgress>,
    @Inject('CRAWL_CUSTOMER_REPOSITORY')
    private crawlCus: Repository<CrawlCustomer>
  ) { }

  async insertRequest(createCrawlDto: CreateCrawlDto) {
    try {
      return await this.crawlRepo.createQueryBuilder()
        .insert()
        .into(CrawlRequest)
        .values([
          {
            customerSeq: createCrawlDto.customer_seq,
            channelSeq: createCrawlDto.channel_seq,
            title: createCrawlDto.title,
            mode: createCrawlDto.mode,
            startDt: createCrawlDto.start_dt,
            endDt: createCrawlDto.end_dt,
            keyword: createCrawlDto.keyword,
            checkMd5: createCrawlDto.check_md5,
            period: createCrawlDto.period,
            typeCd: createCrawlDto.type_cd,
            status: createCrawlDto.status,
            daySchedules: '*',
            monthSchedules: '*',
            yearSchedules: '*'
          }
        ])
        .execute();
    } catch (e) {
      console.log('Insert ERROR');
      throw e;
    }
  }

  async findRequest() {
    try {
      return await this.crawlRepo.find()

    } catch (e) {
      console.log('Find Request ERROR')
      throw e
    }
  }

  async findProgress() {
    try {
      return await this.crawlProg.find();
    } catch (e) {
      console.log('Find Progress ERROR')
      throw e
    }
  }

  async findProgressCustomerCount(id: number) {
    try {
      return await this.crawlProg.createQueryBuilder('progress')
        .innerJoin(CrawlRequest, 'request', 'progress.request_seq = request.seq')
        .where('request.customer_seq IN (:id)', { id: id })
        .getCount();
    } catch (e) {
      console.log()
      throw e
    }
  }

  async findProgressCustomer(id: number) {
    try {
      const mainQuery =
        await this.crawlProg.createQueryBuilder('progress')
          .innerJoin(CrawlRequest, 'request', 'progress.request_seq = request.seq')
          .where('request.customer_seq IN (:id)', { id: id })
          .getMany();
      return mainQuery
    } catch (e) {
      console.log('ProgressCustomer Not Found');
      throw (e)
    }
  }

  async update(id: string, updateCrawlDto: UpdateCrawlDto) {
    try {
      return await this.crawlRepo.createQueryBuilder()
        .update()
        .set({
          status: updateCrawlDto.status,
          schedules: updateCrawlDto.schedules,
          startDt: updateCrawlDto.start_dt,
          endDt: updateCrawlDto.end_dt
        })
        .where("channel_seq = :id", { id: id })
        .execute();
    } catch (e) {
      console.log('Not Updated');
      throw (e);
    }
  }

  async remove(id: string) {
    try {
      return await this.crawlProg.createQueryBuilder()
        .delete()
        .where("request_seq = :id", { id: id })
        .execute();
    } catch (e) {
      console.log("Not Deleted");
      throw (e);
    }
  }

  async insertCustomer(createCustomer: CreateCustomerDto) {
    try {
      return await this.crawlCus.createQueryBuilder()
        .insert()
        .into(CrawlCustomer)
        .values([
          {
            name: createCustomer.name,
            comment: createCustomer.comment,
          }
        ])
        .execute();
    } catch (e) {
      console.log('Insert ERROR');
      throw e;
    }
  }

  async findCustomerTotal() {
    try {
      return await this.crawlCus.find()
    } catch (e) {
      console.log('Insert ERROR');
      throw e;
    }
  }
}

service.spec.ts code

import { Test, TestingModule } from '@nestjs/testing';
import { CrawlsService } from './crawls.service';
import { Repository } from 'typeorm/repository/Repository';
import { CrawlRequest } from './entities/crawlRequest.entity';
import { getRepositoryToken } from '@nestjs/typeorm';

type MockRepository<T = any> = Partial<Record<keyof Repository<T>, jest.Mock>>;


describe('CrawlService', () => {
  let service: CrawlsService;
  let crawlRepository: MockRepository<CrawlRequest>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [CrawlsService,
        {
          provide: getRepositoryToken(CrawlRequest),
          useValue: {
            save: jest.fn().mockResolvedValue(CrawlRequest),
          }

        }]
    }).compile();
    service = module.get<CrawlsService>(CrawlsService);
    crawlRepository = module.get<MockRepository<CrawlRequest>>(getRepositoryToken(CrawlRequest));
  });

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

When I try to test service.spec, I get the following error : "Nest can't resolve dependencies of the CrawlsService (?). Please make sure that the argument CrawlsRepository at index [0] is available in the RootTestModule context.".

I tried a lot of solutions , I can't find the solutions... please let me know the solution... I want to find reason why there is a problem...

I find lot of jest test code files , I tried to use lots of codes.. but I cant test my code..

1

There are 1 best solutions below

0
On

Your provide token should just be the CrawlsRepository class. The getRepositoryToken() is for if you use @InjectRepository()