【问题标题】:NetsJs Controller Unit Testing returning TypeError: Cannot read property of undefinedNestJs 控制器单元测试返回 TypeError:无法读取未定义的属性
【发布时间】:2020-08-28 06:59:00
【问题描述】:

试图在 NetsJs 控制器上编写单元测试但得到 返回 TypeError: Cannot read property 'getGroup' of undefined

groups.controller.spec.ts

describe("GroupsController", () => {
    let groupsController: GroupsController;
    let groupsService: GroupService;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [GroupsController],
            providers: [
                {
                    provide: getRepositoryToken(Groups),
                    useFactory: GroupModelMockFactory
                },
                {
                    provide: getRepositoryToken(Roles),
                    useFactory: roleModelMockFactory
                },
                RSTLogger,
                RolesService,
                GroupService,
                CommonService,
                DatabaseService,
                GroupsController
            ]
        }).compile();

        groupsService = module.get<GroupService>(GroupService);
        groupsController = module.get<GroupsController>(GroupsController);
    });


    it("should be defined", () => {
        expect(groupsController).toBeDefined();
    });

    describe("Find Group", () => {
        it("Get group", async () => {
            try {
                const expectedResult = {
                    groupName: "group123",
                    description: "Group Description",
                    roleId: 1
                };
                 expect(
                    await groupsController.getGroup(1, 'no')
                 ).toEqual({ data: expectedResult });
            } catch (e) {
                console.log(e);
            }
        });
    });
});

unitTestingMocks.ts

export const roleModelMockFactory = () => ({
    findOne: id => ({
      id: "1",
      name: "Name",
      description: "Description",
      resource: []
    }),
    create: RoleDto => ({
      name: "Role1",
      description: "Role Description",
      resource: []
    }),
    save: RoleDto => ({
      name: "Role1",
      description: "Role Description",
      resource: []
    }),
    update: RoleDto => ({
      exec: async () => ({
        name: "Updated Role",
        description: "Role Description",
        resource: []
      })
    }),
    findByIdAndRemove: id => ({
      exec: async () => ({
        name: "Deleted Role",
        description: "Description",
        resource: []
      })
    }),
  });

  export const GroupModelMockFactory = () => ({

    findByRoleId: id => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    findOne: dto => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    create: groupDto => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    save: groupDto => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    findOneOrFail: id => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    update: groupDto => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    delete: id => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    }),
    getGroup: id => ({
      groupName: "group123",
      description: "Group Description",
      roleId: 1
    })
  });

groups.controller.ts

@ApiTags('groups')
@ApiBearerAuth()
@Controller('groups')
@Injectable({ scope: Scope.REQUEST })
export class GroupsController {
    constructor(private readonly groupsService: GroupService,
        private rstLogger: RSTLogger,
        private commonService: CommonService,
        @Inject(REQUEST) private readonly request: Request) {
        this.rstLogger.setContext('GroupController');
    }

    @Get(':groupId')
    @ApiQuery({ name: 'groupId' })
    @ApiQuery({ name: 'relatinalData' , enum: ['yes', 'no']})
    @UseGuards(JWTTokenAuthGuard, RolesGuard)
    async gerGroup(@Query('groupId') groupId, @Query('relatinalData') relatinalFlag) {
        const group = await this.groupsService.getGroup(groupId, relatinalFlag);
        if (!group) throw new NotFoundException('Group does not exist!');
        return { data: group };
    }

}

group.service.ts

export class GroupService {
    constructor(
        @InjectRepository(Groups) private readonly groupModel: Repository<Groups>,
        private rstLogger: RSTLogger,
        private readonly databaseService: DatabaseService,
        private readonly rolesService: RolesService) {
        this.rstLogger.setContext('GroupServices');
    }

    async getGroup(ID, relatinalFlag = 'no'): Promise<Groups> {
        if (relatinalFlag && relatinalData.yes === relatinalFlag) {
            return await this.databaseService.findOneWithRelation(this.groupModel, { id: ID }, { relations: ['role'] });
        } else {
            return await this.databaseService.findOne(this.groupModel, { id: ID });
        }
    }
}

我在尝试从控制器获取组时遇到错误

  TypeError: Cannot read property 'getGroup' of undefined

谁能指导我这里需要纠正的地方。

【问题讨论】:

    标签: unit-testing jestjs nestjs typeorm nestjs-config


    【解决方案1】:

    GroupService 的依赖似乎有自己的依赖。如果它们对这个测试不重要,你可以像这样模拟它们

     {provide: RSTLogger, useValue: jest.fn() },
    

    但正如我所见,DatabaseService 有它自己的依赖项,应该正确提供或模拟。

    【讨论】:

    • 是的,但这里的问题是 groupsController 对象在我尝试打印时返回空对象 {}。
    • 通常表示groupsController 的部分依赖丢失,无法启动对象。研究 RSTLogger、DatabaseService、RolesService 的依赖关系,您会发现其中一些在您的 TestingModule 的提供程序部分中遗漏了
    • 谢谢,我发现问题在于组控制器依赖 @Inject(REQUEST)。我嘲笑它,它现在工作正常。
    猜你喜欢
    • 2021-01-22
    • 2020-01-17
    • 2019-09-16
    • 2015-11-14
    • 2018-04-18
    • 2018-11-11
    • 2021-01-22
    • 1970-01-01
    • 2021-07-23
    相关资源
    最近更新 更多