如何通过sinon存根正在测试的类的私有方法

时间:2019-10-21 09:19:15

标签: angular typescript unit-testing

我正在尝试在类中添加私有方法。我搜索了许多没有正确答案或与我的关注无关的博客。我们可以存根私有方法吗?

这是我的代码,它使用我想存根的私有方法:

public static async create(roleTO: RoleTO): Promise<RoleTO> {
        log.trace('Inside create method with roleTO: ', roleTO);
        roleTO.name = roleTO.name.trim();


     await this.validateIfRoleNameIsTaken(roleTO); //validateIfRoleNameIsTaken it is a private method. I am trying to stub this method


        let rolePO: RoleDocument = <RoleDocument>PoToConverter.getRoleTo2Po(roleTO);
        console.log(rolePO,'this is rolelPO');

        log.trace('Persisting Role: ', rolePO);
      rolePO = await rolePO.persist();
       console.log(rolePO._id,'tydtydytd');

        roleTO._id = rolePO._id;
        console.log(roleTO);
        return roleTO;


    }

这是私有方法的定义:

 private static async validateIfRoleNameIsTaken(role: RoleTO | RolePO): Promise<void> {
        log.trace(`Inside validateIfRoleNameIsTaken method with role: `, role);
        let RoleModel: RoleModel = <RoleModel>model(ROLE_MODEL);

        let existingRoles: RolePO[] = await RoleModel.findByName(role.name);


        log.debug(`Fetched following roles from storage: `, existingRoles);
        ValidationUtil.failIfMatchExists(role.name, existingRoles);
    }

0 个答案:

没有答案