Pass Array to creat function in NestJs Unit Test with Type ORM

518 views Asked by At

In my Typeform create function. I'm accepting an array of objects in my service. but when I try to write a unit test for that it's throwing an error because mockReturnValue only accepts a single object. This is my test spec

export class studentRepositoryFakeFake {
  public async create(): Promise<void> {}
  public async findAll(): Promise<void> {}
  public async save(): Promise<void> {}
  public async update(): Promise<void> {}
  public async remove(): Promise<void> {}
  public async findOne(): Promise<void> {}
}

describe('StudentsService', () => {
  let studentsService: StudentsService;
  let studentsRepository: Repository<Student>;

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

    studentsService = module.get<StudentsService>(StudentsService);
    studentsRepository = module.get(getRepositoryToken(Student));
  });

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

  describe('creating students', () => {
    it('throws an error when there is no payload provided', async () => {});

    it('call parameter with correct payload', async () => {
      const students:Student[] = [
        {id:5, name: 'User Name 1', email: '[email protected]', dob: '2001-10-2',age:20 },
      ];
      const studentRepositoryCreateSpy = jest.spyOn(studentsRepository,'create').mockReturnValue(students)
      const studentRepositorySpy = jest.spyOn(studentsRepository,'save').mockResolvedValue(students)
    });
  });
});

Service that I'm trying to write the unit test

 constructor(
    @InjectRepository(Student) private studentRespository: Repository<Student>,
  ) {}

  async create(createStudentInput: CreateStudentInput[]): Promise<Student[]> {
    const students = await this.studentRespository.create(createStudentInput);
    return await this.studentRespository.save(students);
  }
0

There are 0 answers