代码之家  ›  专栏  ›  技术社区  ›  Alpin Cleopatra

如何使用Jest和NestJS模拟注入存储库?

  •  0
  • Alpin Cleopatra  · 技术社区  · 3 年前

    在NestJS项目中,使用Jest测试服务案例。我创建了一个find方法,并在解析器(GraphQL)函数中使用它。在测试解析器时,它在服务中找不到find方法。

    src/serivce/post.ts

        import { Injectable } from '@nestjs/common';
        import { InjectRepository } from '@nestjs/typeorm';
    
        import { AbstractPostRepository } from '@abstractRepository/AbstractPostRepository';
        import { PostRepository } from '@repository/PostRepository';
    
        @Injectable()
        export class PostService {
          constructor(
            @InjectRepository(PostRepository)
            private postRepo: AbstractPostRepository,
          ) {}
    
          async findById(id: string) {
            const posts = await this.postRepo.findById(id);
    
            ......
            return posts;
          }
        }
    

    src/resolver/query/post.ts

        import { Args, Query, Resolver } from '@nestjs/graphql';
    
        import { Authorized } from '@lib/auth/authorized';
        import { PermissionScope } from '@lib/auth/permissionScope';
        import { PostService } from '@service/postService';
    
        @Resolver()
        export class PostsResolver {
          constructor(private postService: PostService) {}
    
          @PermissionScope()
          @Authorized([
            PermissionEnum.READ_MANAGEMENT,
          ])
          @Query()
          async findPosts() {
             return await this.postService.findById(id);
          }
        }
    

    与此服务相关的解析器的单元测试:

    测试/单元/解析器/post.spec.ts

        import { Test, TestingModule } from '@nestjs/testing';
    
        import { PERMISSION_MANAGER } from '@lib/auth/permissionManager.module';
        import { PostsResolver } from '@resolver/query/post';
        import { PostService } from '@service/postService';
    
        describe('PostsResolver', () => {
          let resolver: PostsResolver;
    
          beforeEach(async () => {
            const module: TestingModule = await Test.createTestingModule({
              providers: [
                PostsResolver,
                {
                  provide: PERMISSION_MANAGER,
                  useValue: jest.fn(),
                },
                {
                  provide: PostService,
                  useFactory: () => ({
                    findById: jest.fn(() => [
                      {
                        id: '11111111-1111-1111-1111-111111111111',
                        name: 'name1',
                      },
                    ]),
                  }),
                },
              ],
            }).compile();
    
            resolver = module.get<PostsResolver>(PostsResolver);
          });
    
          describe('findPosts', () => {
            it('should return data', async () => {
              const posts = await resolver.findPosts({
                id: '11111111-1111-1111-1111-111111111111',
              });
    
              const expected = [
                {
                  id: '11111111-1111-1111-1111-111111111111',
                  name: 'name1',
                },
              ];
    
              expect(posts).toEqual(expected);
            });
          });
        });
    

    运行此测试时出现错误:

      ● PostsResolver › findPosts › should return data
    
        TypeError: Cannot read properties of undefined (reading 'findById')
    
          22 |     { id }: FindPostsInput,
          23 |   ) {
        > 24 |     return await this.postService.findById(
             |                                         ^
          25 |       id,
          26 |     );
    
          at PostsResolver.findPosts (src/resolver/query/post.ts:24:41)
          at Object.<anonymous> (test/unit/resolver/post.spec.ts:59:42)
    

    这似乎是模拟服务 findById 在中 Test.createTestingModule 不起作用。如何正确地模仿?是否与某些注射原因有关?

    0 回复  |  直到 3 年前