热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

SpyOnTypeORM存储库更改单元测试NestJS的返回值

如何解决《SpyOnTypeORM存储库更改单元测试NestJS的返回值》经验,为你挑选了1个好方法。



1> 小智..:

好吧,终于经过测试并尝试了各种想法之后,我发现这是一个有效的策略

    假设我们已经建立了一个PhotoEntity具有基本属性,没有什么特别的东西(id,名称,描述等)

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Photo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 500 })
  name: string;

  @Column('text')
  description: string;

  @Column()
  filename: string;

  @Column('int')
  views: number;

  @Column()
  isPublished: boolean;
}

    设置PhotoService如下所示的内容(超级基础,但这将说明要点):

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Photo } from './photo.entity';

@Injectable()
export class PhotoService {
  constructor(
    @InjectRepository(Photo)
    private readonly photoRepository: Repository,
  ) {}

  async findAll(): Promise {
    return await this.photoRepository.find();
  }
}

    我们可以useClass: Repository这样,我们不必做任何繁重的工作来设置用于测试的存储库类(存储库是从TypeORM包中导入的。然后,我们可以从模块中获取存储库并将其保存为一个值为了轻松模拟并像这样设置我们的测试:

import { Test, TestingModule } from '@nestjs/testing';
import { PhotoService } from './photo.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Photo } from './photo.entity';
import { Repository } from 'typeorm';

describe('PhotoService', () => {
  let service: PhotoService;
  // declaring the repo variable for easy access later
  let repo: Repository;

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

    service = module.get(PhotoService);
    // Save the instance of the repository and set the correct generics
    repo = module.get>(getRepositoryToken(Photo));
  });

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

  it('should return for findAll', async () => {
    // mock file for reuse
    const testPhoto: Photo =  {
      id: 'a47ecdc2-77d6-462f-9045-c440c5e4616f',
      name: 'hello',
      description: 'the description',
      isPublished: true,
      filename: 'testFile.png',
      views: 5,
    };
    // notice we are pulling the repo variable and using jest.spyOn with no issues
    jest.spyOn(repo, 'find').mockResolvedValueOnce([testPhoto]);
    expect(await service.findAll()).toEqual([testPhoto]);
  });
});

    针对指定文件或所有测试运行测试

? npm run test -- photo.service

> nestjs-playground@0.0.1 test ~/Documents/code/nestjs-playground
> jest "photo.service"

 PASS  src/photo/photo.service.spec.ts
  PhotoService
    ? should be defined (17ms)
    ? should return for findAll (4ms)  <-- test passes with no problem

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.372s, estimated 4s
Ran all test suites matching /photo.service/i.


推荐阅读
author-avatar
mobiledu2502857983
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有