Alurachallenges chen 2(Semana 2)


前の前の、nのもののfizemos todasは、前に、thenneを結びつけます.
第二次世界大戦についての一考察
ヘーゲル『セギュンテ』におけるデリア・セマナ

Depois de alguns testes com usuários, foi definido que a próxima feature a ser desenvolvida nesse projeto é a divisão dos vídeos por categoria, para melhorar a experiência de organização da lista de vídeos pelo usuário.


ENTはO、Oは、seguintesとしてimplementações :

  • 副詞categorias セウス・カンポスベース

  • ロトラス/categorias ;

  • インペリアルカンポcategoriaId 無モデロvideo ;

  • EscreverのOSは、ユニット単位riosです.
  • vamosは、ar ar fazendo os dois primeiros pontos、e novamente usaremos oを生成します.
    nest generate resource categorias
    
    a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a
    // src/categorias/dto/create-categoria.dto.ts
    
    import { Video } from '../../videos/entities/video.entity';
    
    export class CreateCategoriaDto {
      id: number;
      titulo: string;
      cor: string;
      videos: Video[];
    }
    
    
    e alteraremos o nosso createVideoto , adicionando a分類:
    // src/videos/dto/create-video.dto.ts
    
    import { Categoria } from '../../categorias/entities/categoria.entity';
    
    export class CreateVideoDto {
    ...
    
    categoria: Categoria;
    }
    
    アゴラvamos na nossa「実体」eプリキスモスfazer um Pulco Diferente.
    <研究ノート>リ・ライガーの作品としての作品としての作品
    // src/categorias/entities/categoria.entity.ts
    
    import { IsNotEmpty, IsString } from 'class-validator';
    import { Video } from '../../videos/entities/video.entity';
    import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from 'typeorm';
    
    @Entity()
    export class Categoria {
      @PrimaryGeneratedColumn()
      id: number;
    
      @IsNotEmpty()
      @IsString()
      @Column()
      titulo: string;
    
      @IsNotEmpty()
      @IsString()
      @Column()
      cor: string;
    
      @OneToMany(() => Video, (video) => video.categoria)
      videos: Video[];
    }
    
    Ser - en - necess - rio - alterar nossa "entity "video tamb are m , informando que teremos varios v . de deos para cada分類使用しています.
    // src/videos/entities/video.entity.ts
    
    import { PrimaryGeneratedColumn, Column, Entity, ManyToOne } from 'typeorm';
    import { IsNotEmpty, IsString, IsUrl } from 'class-validator';
    import { Categoria } from '../../categorias/entities/categoria.entity';
    
    @Entity()
    export class Video {
      ...
      @ManyToOne(() => Categoria, (categoria) => categoria.id, { nullable: false })
      categoria: Categoria;
    }
    
    Fencionalidades delaとして、Ajustadas、vamos para o nosso「分類」.
    ディフェレンス・アヌ・エス・エス・ファンドール『メトロ・インディアナト』レア・ポエム・O (リレーションズ:[ビデオ] ])
    // src/categorias/categorias.service.ts
    
    import { Injectable } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { CreateCategoriaDto } from './dto/create-categoria.dto';
    import { UpdateCategoriaDto } from './dto/update-categoria.dto';
    import { Categoria } from './entities/categoria.entity';
    
    @Injectable()
    export class CategoriasService {
      @InjectRepository(Categoria)
      private categoriaRepository: Repository<Categoria>;
    
      create(createCategoriaDto: CreateCategoriaDto) {
        return this.categoriaRepository.save(createCategoriaDto);
      }
    
      findAll() {
        return this.categoriaRepository.find({
          relations: ['videos'],
          loadEagerRelations: true,
        });
      }
    
      findOne(id: number) {
        return this.categoriaRepository.findOne(id);
      }
    
      update(id: number, updateCategoriaDto: UpdateCategoriaDto) {
        return this.categoriaRepository.update(id, updateCategoriaDto);
      }
    
      async remove(id: number) {
        const categoria = await this.findOne(id);
        return this.categoriaRepository.remove(categoria);
      }
    }
    
    Novamente , Temos que Ajustar nosso "Video . Service "Tamb Le m , que no caso , s no ter ter a altera pose o o m m todo "findall ():
    // src/videos/videos.service.ts
    
    ...
    findAll() {
        return this.videoRepository.find({
          relations: ['categoria'],
          loadEagerRelations: true,
        });
      }
    ...
    
    アゴラ、パラqueは、タブラデCatadaのBanco e Identificadaペロ巣、プレステージamir範疇でタブラを分類します.モジュールE INPROFILE O TYPE MOTOR PARTADAN PARTIA COUNT PAR MORE PARMAT :
    // src/categorias/categorias.module.ts
    
    import { Module } from '@nestjs/common';
    import { CategoriasService } from './categorias.service';
    import { CategoriasController } from './categorias.controller';
    import { Categoria } from './entities/categoria.entity';
    import { TypeOrmModule } from '@nestjs/typeorm';
    
    @Module({
      imports: [TypeOrmModule.forFeature([Categoria])],
      controllers: [CategoriasController],
      providers: [CategoriasService],
    })
    export class CategoriasModule {}
    
    
    Maravilha , Improentamos as nonos s video , por lesm m , temos um que que de de que que ao ao acessar a rota "/category orias/id/video "retorne os v ' de deos de uma determinada分類

    Para que isso seja possは、ベル、Vamosプリザールデ馬ノヴァロタノnossoコントローラデ範疇で.
    ノヴァ・ロタ・ブイ
    // src/categorias/categorias.controller.ts
    ...
    
    @Get(':id/videos')
      findVideosByCategoryId(@Param('id') id: string) {
        return this.categoriasService.findVideoByCategory(+id);
      }
    
    ...
    
    Ma espera A , N ' s s n n o Temos Ese m To do do do do "do "
    Premiisamos Criar Esse M To do no no nosserservi
    // src/categorias/categorias.service.ts
    
    ...
    
    async findVideoByCategory(id: number): Promise<Video[]> {
        const categoria = await this.findOne(id);
        return categoria.videos;
      }
    
    ...
    
    ロゼ、Veremos Uaテル・ブランカ、SEM Rettorno de Nenhum Dado
    パラ・クック・レトルネード著『トド・フィンドン』について
    <研究ノート>トド・フィカエとアッシム:
    // src/categorias/categorias.service.ts
    ...
    
    findOne(id: number) {
        return this.categoriaRepository.findOne(id, {
          relations: ['videos'],
          loadEagerRelations: true,
        });
      }
    
    ...
    
    アゴラSim、Ao Aceessar Nossa Rota「.../範疇/1/ビデオ」、teremos nossos vは、deos参照について言及します.
    <高橋潤子>

    People - TenderのESSE Latsisito , PremiisAreas Overar NSSOコントローラE NOSSOサービスビデオ
    // src/videos/videos.controller.ts
    
    ...
    
    @Get()
      findAll(@Query() query) {
        return this.videosService.findAll(query.search);
      }
    
    ...
    
    // src/videos/videos.service.ts
    
    ...
    
    findAll(search = '') {
        return this.videoRepository.find({
          where: { titulo: ILike(`%${search}%`) },
          relations: ['categoria'],
        });
      }
    
    ...
    
    <高橋潤子>

    コモJは、Criamos UMAカテゴリーIAの前で、Vamos Enviar Tuma Litsiは、oを更新します

    E APは、s isso、vamosなしビデオです.Service e AlterareMOS A GRACE GICA DO M Take todo create :
    // src/videos/videos.service.ts
    ...
    
    create(createVideoDto: CreateVideoDto) {
        if (!createVideoDto.categoria)
          return this.videoRepository.save({
            ...createVideoDto,
            categoria: { id: 1 },
          });
        return this.videoRepository.save(createVideoDto);
      }
    
    ...
    
    prento to atendido!

    (Faça uma requisição criando um vídeo sem informar a categoria e veja se está tudo funcionando como o esperado, o retorno deve ser o vídeo criado e com a "categoria":{"id": 1})


    <研究ノート>第一原理としてのオートミールについて

    コンテナーメント
    Noisas Endades , Deixando Elas Aassimとして
    // src/categorias/entities/categoria.entity.ts
    
    ...
    
    constructor(private categoria?: Partial<Categoria>) {}
    
    // src/categorias/entities/categoria.entity.ts
    
    ...
    
    constructor(private video?: Partial<Categoria>) {}
    
    Vamos Criar Tamb - m - uma - uma common dentro de src e nela criar umaパスタテスト,que ficar no o os arquivos necess are rio e comum no toos os testesPor Agora , Teremos Doisのスタブ:
    ビデオ.スタブT . E .アーキヴォー
    // src/common/test/videos.stub.ts
    
    import { Categoria } from '../../categorias/entities/categoria.entity';
    import { Video } from '../../videos/entities/video.entity';
    import { categoriasStub } from './categorias.stub';
    
    export const videosStub: Video[] = [
      new Video({
        id: 1,
        titulo: 'título qualquer',
        descricao: 'descrição qualquer',
        url: 'http://url_qualquer.com',
        categoria: new Categoria({ id: 1, titulo: 'LIVRE', cor: 'verde' }),
      }),
      new Video({
        id: 2,
        titulo: 'outro título qualquer',
        descricao: 'outra descrição qualquer',
        url: 'http://outra_url_qualquer.com',
        categoria: categoriasStub[1],
      }),
      new Video({
        id: 3,
        titulo: 'titulo qualquer',
        descricao: 'descrição qualquer',
        url: 'http://url_qualquer.com',
        categoria: categoriasStub[1],
      }),
    ];
    
    
    Eカテゴリー.スタブ理研
    // src/common/test/categorias.stub.ts
    
    import { Categoria } from '../../categorias/entities/categoria.entity';
    
    export const categoriasStub: Categoria[] = [
      new Categoria({ id: 1, titulo: 'LIVRE', cor: 'verde' }),
      new Categoria({ id: 2, titulo: 'Programação', cor: 'azul' }),
    ];
    
    
    

    testando OSコントローラ
    vamos rodas os testes e ver no que vai darを使用しています.
    npm run test
    
    que delは、CIA、NenhumテスターPassou!
    ISSO acontece pois alteramamos tudo sem criar nenhum teste o que n no o o muito law,mas enfim,vamosは,coisaとしてajustarを取得した.

    TESTRELO NOSSO範疇コントローラ
    NestJJ J . de ' exia Ua Estrutura Per - es - Monada , Eent So o o , Vamos ' s no nosso Arquivo範疇コントローラ.Per . tsパラtralalharネール.
    NOSSOコントローラTEM COMOは、NIA CIA Eサービスパラシュートで降下します.
    デリフォーム
    // src/categorias/categorias.controller.spec.ts
    
    import { Test, TestingModule } from '@nestjs/testing';
    import { categoriasStub } from '../common/test/categorias.stub';
    import { CategoriasController } from './categorias.controller';
    import { CategoriasService } from './categorias.service';
    import { videosStub } from '../common/test/videos.stub';
    
    describe('CategoriasController', () => {
      let controller: CategoriasController;
      let service: CategoriasService;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          controllers: [CategoriasController],
          providers: [
            CategoriasService,
            {
              provide: CategoriasService,
              useValue: {
                create: jest.fn().mockResolvedValue(categoriasStub[0]),
                findAll: jest.fn().mockResolvedValue(categoriasStub),
                findOne: jest.fn().mockResolvedValue(categoriasStub[0]),
                findVideoByCategory: jest.fn().mockResolvedValue(videosStub),
                update: jest.fn().mockResolvedValue(categoriasStub[0]),
                remove: jest.fn().mockResolvedValue(categoriasStub[0]),
              },
            },
          ],
        }).compile();
    
        controller = module.get<CategoriasController>(CategoriasController);
        service = module.get<CategoriasService>(CategoriasService);
      });
    
      it('should be defined', () => {
        expect(controller).toBeDefined();
        expect(service).toBeDefined();
      }); 
    });
    
    Repare que n n ' s s criamos um mock para cada楽しみは、そうでありません.
    com isso、podemos rodar novamente o comadde testesはnpm、sのアゴラ、deixaremosのエレモダオ時計をパラシュートとして見る.
    npm run test:watch -t /home/gabriel/Documentos/alura-challenges-2/src/categorias/categorias.controller.spec.ts
    
    # substitua essa parte '/home/gabriel/Documentos' pelo caminho do seu computador, é claro.
    
    feito isso、o - teste vai rodar e faremosは、実装者のpositoro oである.
    最終的な、ESSE Arquivo Ficar
    // src/categorias/categorias.controller.spec.ts
    
    import { Test, TestingModule } from '@nestjs/testing';
    import { categoriasStub } from '../common/test/categorias.stub';
    import { CategoriasController } from './categorias.controller';
    import { CategoriasService } from './categorias.service';
    import { videosStub } from '../common/test/videos.stub';
    
    describe('CategoriasController', () => {
      let controller: CategoriasController;
      let service: CategoriasService;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          controllers: [CategoriasController],
          providers: [
            CategoriasService,
            {
              provide: CategoriasService,
              useValue: {
                create: jest.fn().mockResolvedValue(categoriasStub[0]),
                findAll: jest.fn().mockResolvedValue(categoriasStub),
                findOne: jest.fn().mockResolvedValue(categoriasStub[0]),
                findVideoByCategory: jest.fn().mockResolvedValue(videosStub),
                update: jest.fn().mockResolvedValue(categoriasStub[0]),
                remove: jest.fn().mockResolvedValue(categoriasStub[0]),
              },
            },
          ],
        }).compile();
    
        controller = module.get<CategoriasController>(CategoriasController);
        service = module.get<CategoriasService>(CategoriasService);
      });
    
      it('should be defined', () => {
        expect(controller).toBeDefined();
        expect(service).toBeDefined();
      }); 
    
      describe('create', () => {
        it('should create a category', async () => {
          const result = await service.create(categoriasStub[0]);
          expect(result).toEqual(categoriasStub[0]);
          expect(service.create).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'create').mockRejectedValueOnce(new Error());
          expect(service.create(categoriasStub[0])).rejects.toThrowError();
          expect(service.create).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findAll', () => {
        it('should return a category list', async () => {
          const result = await service.findAll();
          expect(result).toEqual(categoriasStub);
          expect(service.findAll).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'findAll').mockRejectedValueOnce(new Error());
          expect(service.findAll()).rejects.toThrowError();
          expect(service.findAll).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findOne', () => {
        it('should return a category', async () => {
          const result = await service.findOne(categoriasStub[0].id);
          expect(result).toEqual(categoriasStub[0]);
          expect(service.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'findOne').mockRejectedValueOnce(new Error());
          expect(service.findOne(1)).rejects.toThrowError();
          expect(service.findOne).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findVideosByCategoryId', () => {
        it('should return videos from a category', async () => {
          const result = await service.findVideoByCategory(categoriasStub[0].id);
          expect(result).toEqual(videosStub);
          expect(service.findVideoByCategory).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest
            .spyOn(service, 'findVideoByCategory')
            .mockRejectedValueOnce(new Error());
          expect(service.findVideoByCategory(1)).rejects.toThrowError();
          expect(service.findVideoByCategory).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('update', () => {
        it('should return a updated category', async () => {
          const result = await service.update(
            categoriasStub[0].id,
            categoriasStub[0],
          );
          expect(result).toEqual(categoriasStub[0]);
          expect(service.update).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'update').mockRejectedValueOnce(new Error());
          expect(service.update(1, categoriasStub[0])).rejects.toThrowError();
          expect(service.update).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('remove', () => {
        it('should return a removed category', async () => {
          const result = await service.remove(categoriasStub[0].id);
          expect(result).toEqual(categoriasStub[0]);
          expect(service.remove).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'remove').mockRejectedValueOnce(new Error());
          expect(service.remove(1)).rejects.toThrowError();
          expect(service.remove).toHaveBeenCalledTimes(1);
        });
      });
    });
    
    
    Pasou Todos OSのテスト?vamosパラo prは、Ximoをします!

    testando nossoビデオ.コントローラ
    npm run test:watch -t /home/gabriel/Documentos/alura-challenges-2/src/videos/videos.controller.spec.ts
    
    # substitua essa parte '/home/gabriel/Documentos' pelo caminho do seu computador, é claro.
    
    <論文>中庸パラダイムとして
    // src/videos/videos.controller.spec.ts
    
    import { Test, TestingModule } from '@nestjs/testing';
    import { VideosController } from './videos.controller';
    import { VideosService } from './videos.service';
    import { videosStub } from '../common/test/videos.stub';
    
    describe('VideosController', () => {
      let controller: VideosController;
      let service: VideosService;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          controllers: [VideosController],
          providers: [
            VideosService,
            {
              provide: VideosService,
              useValue: {
                create: jest.fn().mockResolvedValue(videosStub[0]),
                findAll: jest.fn().mockResolvedValue(videosStub),
                findOne: jest.fn().mockResolvedValue(videosStub[0]),
                update: jest.fn().mockResolvedValue(videosStub[0]),
                remove: jest.fn().mockResolvedValue(videosStub[0]),
              },
            },
          ],
        }).compile();
    
        controller = module.get<VideosController>(VideosController);
        service = module.get<VideosService>(VideosService);
      });
    
      it('should be defined', () => {
        expect(controller).toBeDefined();
        expect(service).toBeDefined();
      });
    
      describe('create', () => {
        it('should create a video', async () => {
          const result = await service.create(videosStub[0]);
          expect(result).toEqual(videosStub[0]);
          expect(service.create).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'create').mockRejectedValueOnce(new Error());
          expect(service.create(videosStub[0])).rejects.toThrowError();
          expect(service.create).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findAll', () => {
        it('should return a video list', async () => {
          const result = await service.findAll();
          expect(result).toEqual(videosStub);
          expect(service.findAll).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'findAll').mockRejectedValueOnce(new Error());
          expect(service.findAll()).rejects.toThrowError();
          expect(service.findAll).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findOne', () => {
        it('should return a video', async () => {
          const result = await service.findOne(videosStub[0].id);
          expect(result).toEqual(videosStub[0]);
          expect(service.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'findOne').mockRejectedValueOnce(new Error());
          expect(service.findOne(1)).rejects.toThrowError();
          expect(service.findOne).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('update', () => {
        it('should return a updated video', async () => {
          const result = await service.update(videosStub[0].id, videosStub[0]);
          expect(result).toEqual(videosStub[0]);
          expect(service.update).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'update').mockRejectedValueOnce(new Error());
          expect(service.update(1, videosStub[0])).rejects.toThrowError();
          expect(service.update).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('remove', () => {
        it('should return a removed video', async () => {
          const result = await service.remove(videosStub[0].id);
          expect(result).toEqual(videosStub[0]);
          expect(service.remove).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(service, 'remove').mockRejectedValueOnce(new Error());
          expect(service.remove(1)).rejects.toThrowError();
          expect(service.remove).toHaveBeenCalledTimes(1);
        });
      });
    });
    
    
    Teites DOSコントローラOK、VAMOSパラOSサービス.

    TESTARIO OSサービス
    としてSEM Muitas Mudanは、C Cのタムムームm、faemos o mesmo que NOSコントローラ、非常にPelo Fato de que aに依存しているNCIA deixa de ser o servi - e o((反bvio、pois estamos no servi - se - rs)e passer a ser nonosoリポジトリ.
    Trechoパラシュートで降下する人
    // src/categorias/categorias.service.spec.ts
    
    ...
    
    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            CategoriasService,
            {
              provide: getRepositoryToken(Categoria),
              useValue: {
                save: jest.fn().mockResolvedValue(categoriasStub[0]),
                find: jest.fn().mockResolvedValue(categoriasStub),
                findOne: jest.fn().mockResolvedValue(categoriasStub[0]),
                update: jest.fn().mockResolvedValue(categoriasStub[0]),
                remove: jest.fn().mockResolvedValue(categoriasStub[0]),
              },
            },
          ],
        }).compile();
    
        service = module.get<CategoriasService>(CategoriasService);
        repository = module.get(getRepositoryToken(Categoria));
      });
    
    ...
    
    DADA A devida atenは、o o o o o o o que muda dosコントローラ、実装者としてのVAMOSパラシュートです.

    TESTRELO NOSSO範疇サービス
    npm run test:watch -t /home/gabriel/Documentos/alura-challenges-2/src/categorias/categorias.service.spec.ts
    
    # substitua essa parte '/home/gabriel/Documentos' pelo caminho do seu computador, é claro.
    
    <研究ノート>フィカール・ア・アッシムの作品について
    // src/categorias/categorias.service.spec.ts
    
    import { Test, TestingModule } from '@nestjs/testing';
    import { CategoriasService } from './categorias.service';
    import { getRepositoryToken } from '@nestjs/typeorm';
    import { Categoria } from './entities/categoria.entity';
    import { categoriasStub } from '../common/test/categorias.stub';
    import { Repository } from 'typeorm';
    
    describe('CategoriasService', () => {
      let service: CategoriasService;
      let repository: Repository<Categoria>;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            CategoriasService,
            {
              provide: getRepositoryToken(Categoria),
              useValue: {
                save: jest.fn().mockResolvedValue(categoriasStub[0]),
                find: jest.fn().mockResolvedValue(categoriasStub),
                findOne: jest.fn().mockResolvedValue(categoriasStub[0]),
                update: jest.fn().mockResolvedValue(categoriasStub[0]),
                remove: jest.fn().mockResolvedValue(categoriasStub[0]),
              },
            },
          ],
        }).compile();
    
        service = module.get<CategoriasService>(CategoriasService);
        repository = module.get(getRepositoryToken(Categoria));
      });
    
      it('should be defined', () => {
        expect(service).toBeDefined();
        expect(repository).toBeDefined();
      });
    
      describe('save', () => {
        it('should create a category', async () => {
          const newCategory: Omit<Categoria, 'id'> = categoriasStub[0];
    
          const result = await service.create(newCategory);
    
          expect(result).toEqual(categoriasStub[0]);
          expect(repository.save).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'save').mockRejectedValueOnce(new Error());
          expect(service.create(categoriasStub[0])).rejects.toThrowError();
          expect(repository.save).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findAll', () => {
        it('should return a categories list', async () => {
          const result = await service.findAll();
          expect(result).toEqual(categoriasStub);
          expect(repository.find).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'find').mockRejectedValueOnce(new Error());
          expect(service.findAll()).rejects.toThrowError();
          expect(repository.find).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findOne', () => {
        it('should return a category', async () => {
          const result = await service.findOne(categoriasStub[0].id);
          expect(result).toEqual(categoriasStub[0]);
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'findOne').mockRejectedValueOnce(new Error());
          expect(service.findOne(1)).rejects.toThrowError();
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('update', () => {
        it('should return a updated category', async () => {
          const result = await service.update(
            categoriasStub[0].id,
            categoriasStub[0],
          );
          expect(result).toEqual(categoriasStub[0]);
          expect(repository.update).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'update').mockRejectedValueOnce(new Error());
          expect(service.update(1, categoriasStub[0])).rejects.toThrowError();
          expect(repository.update).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('remove', () => {
        it('should return a removed category', async () => {
          const result = await service.remove(categoriasStub[0].id);
          expect(result).toEqual(categoriasStub[0]);
          expect(repository.remove).toHaveBeenCalledTimes(1);
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'remove').mockRejectedValueOnce(new Error());
          expect(service.remove(1)).rejects.toThrowError();
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
      });
    });
    

    testando nossoビデオ.サービス
    Eパラオo noistsは、サービスデビデオをします
    npm run test:watch -t /home/gabriel/Documentos/alura-challenges-2/src/videos/videos.service.spec.ts
    
    # substitua essa parte '/home/gabriel/Documentos' pelo caminho do seu computador, é claro.
    
    // src/videos/videos.service.spec.ts
    
    import { Test, TestingModule } from '@nestjs/testing';
    import { getRepositoryToken } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import { videosStub } from '../common/test/videos.stub';
    import { Video } from './entities/video.entity';
    import { VideosService } from './videos.service';
    
    describe('VideosService', () => {
      let service: VideosService;
      let repository: Repository<Video>;
    
      beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
          providers: [
            VideosService,
            {
              provide: getRepositoryToken(Video),
              useValue: {
                save: jest.fn().mockResolvedValue(videosStub[0]),
                find: jest.fn().mockResolvedValue(videosStub),
                findOne: jest.fn().mockResolvedValue(videosStub[0]),
                update: jest.fn().mockResolvedValue(videosStub[0]),
                remove: jest.fn().mockResolvedValue(videosStub[0]),
              },
            },
          ],
        }).compile();
    
        service = module.get<VideosService>(VideosService);
        repository = module.get(getRepositoryToken(Video));
      });
    
      it('should be defined', () => {
        expect(service).toBeDefined();
        expect(repository).toBeDefined();
      });
    
      describe('save', () => {
        const newVideo: Omit<Video, 'id'> = videosStub[0];
    
        it('should create a video', async () => {
          const result = await service.create(newVideo);
          expect(result).toEqual(videosStub[0]);
          expect(repository.save).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'save').mockRejectedValueOnce(new Error());
          expect(service.create(videosStub[0])).rejects.toThrowError();
          expect(repository.save).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findAll', () => {
        it('should return a videos list if search is not informed', async () => {
          const result = await service.findAll();
          expect(result).toEqual(videosStub);
          expect(repository.find).toHaveBeenCalledTimes(1);
        });
    
        it('should return a videos list if search is informed', async () => {
          //Arrange
          const expectedResult = videosStub.filter((video) =>
            video.titulo?.includes('teste'),
          );
          jest.spyOn(repository, 'find').mockResolvedValue(expectedResult);
    
          //Act
          const result = await service.findAll('teste');
    
          //Assert
          expect(result).toEqual([]);
          expect(repository.find).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'find').mockRejectedValueOnce(new Error());
          expect(service.findAll()).rejects.toThrowError();
          expect(repository.find).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('findOne', () => {
        it('should return a video', async () => {
          const result = await service.findOne(videosStub[0].id);
          expect(result).toEqual(videosStub[0]);
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'findOne').mockRejectedValueOnce(new Error());
          expect(service.findOne(1)).rejects.toThrowError();
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('update', () => {
        it('should return a updated video', async () => {
          const result = await service.update(videosStub[0].id, videosStub[0]);
          expect(result).toEqual(videosStub[0]);
          expect(repository.update).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'update').mockRejectedValueOnce(new Error());
          expect(service.update(1, videosStub[0])).rejects.toThrowError();
          expect(repository.update).toHaveBeenCalledTimes(1);
        });
      });
    
      describe('remove', () => {
        it('should return a removed video', async () => {
          const result = await service.remove(videosStub[0].id);
          expect(result).toEqual(videosStub[0]);
          expect(repository.remove).toHaveBeenCalledTimes(1);
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
    
        it('should throw an exception', () => {
          jest.spyOn(repository, 'remove').mockRejectedValueOnce(new Error());
          expect(service.remove(1)).rejects.toThrowError();
          expect(repository.findOne).toHaveBeenCalledTimes(1);
        });
      });
    });
    
    E com isso、実装者としてのfechamosは、es - segunda semanaです.
    Aaaah、Estou fazendo meusは、Coisasとしてconforme vou implementandoを決意します.『パンドロナデインホー』について
    エスト・スル・LGithub .
    アブララSemanaのprの上でabraは、sのe e!