如何解决nestjs单元测试中的类型错误问题?

How to resolve the type error issue in nestjs unit test?

我正在尝试为以下方法创建一个笑话测试。我在两种情况下都出错了。

所以基本上在 checkKioskUserPhone 方法中,

  1. 按phone号查找用户(commonService.findKioskUserByPhone)

  2. 在 findKioskUserByPhone 方法中,我们将通过 phone 号码查找用户,并在未注册或已注册时发送错误消息。

  3. 然后是 return 用户。

  4. (返回 checkKioskUserPhone)如果用户没有授权码和 PIN 码,我们将发送 him/her 授权码和 return jwt,等等

    async checkKioskUserPhone(kioskLoginDto: KioskLoginDto): Promise<ResponseDto<UserAuthDto>> {
        const user = await this.commonService.findKioskUserByPhone(kioskLoginDto);

        const isConfirmedAuthCode = user.authCode === 'OK' ? true : false;
        const isSetPin = user.pin ? true : false;

        if (!isConfirmedAuthCode && !isSetPin) {
            await this.userService.authenticatePhone(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
        }

        const jwtInfo = await this.createToken(this.removeCredentialField(user));

        return Builder<ResponseDto<UserAuthDto>>(ResponseDto)
            .result(Builder(UserAuthDto).isConfirmedAuthCode(isConfirmedAuthCode).isSetPin(isSetPin).jwtInfo(jwtInfo).build())
            .build();
    }


    async findKioskUserByPhone(kioskLoginDto: KioskLoginDto): Promise<User> {
        const user = await this.userService.findOne({ where: { phone: kioskLoginDto.phone } });

        // throw Error message when unregistered phone attempt to login
        if (!user) {
            throw new NotFoundException('User not found');
        }
        // throw Error message when registered phone by whatsapp attempt to login
        if (user.provider !== Provider.KIOSK) {
            throw new ConflictException('You are already joined by Whatsapp.');
        }

        return user;
    }

笑话代码

        it('when unregistered phone attempt to login', async () => {
            const phone = '2212223333';
            const kioskLoginDto = Builder(KioskLoginDto).phone(phone).build();

            service.commonService.findKioskUserByPhone = jest.fn().mockResolvedValue(null);

            try {
                await service.checkKioskUserPhone(kioskLoginDto);
                expect('here').not.toBe('here');
            } catch (error) {
                expect(error).toBeInstanceOf(NotFoundException);
                expect(error.message).toContain('User not found');
            }
        });

        it('When registered phone by app attempt to login', async () => {
            const phone = '2212223333';
            const kioskLoginDto = Builder(KioskLoginDto).phone(phone).build();
            const user = Builder(User).phone(phone).provider(Provider.WHATSAPP).build();

            service.commonService.findKioskUserByPhone = jest.fn().mockResolvedValue(user);

            try {
                await service.checkKioskUserPhone(kioskLoginDto);
                expect('here').not.toBe('here');
            } catch (error) {
                expect(error).toBeInstanceOf(ConflictException);
                expect(error.message).toContain('You are already joined by Whatsapp.');
            }
        });

Jest 错误截图

您正在将 findKioskUserByPhone 方法重写为 return null:

       service.commonService.findKioskUserByPhone = jest.fn().mockResolvedValue(null);

所以 findKioskUserByPhone 永远不会 运行,模拟函数只是 returning null,因此永远不会抛出您期望的错误。相反,这里:

    const user = await this.commonService.findKioskUserByPhone(kioskLoginDto);

用户设置为 null,这里:

    const isConfirmedAuthCode = user.authCode === 'OK' ? true : false;

您正在尝试访问 null 的某些 authCode 属性,这会抛出您得到的 TypeError

您可能打算覆盖用户服务上的 findOne 方法:

       service.userService.findOne = jest.fn().mockResolvedValue(null);

所以你想要的错误实际上会抛出 findKioskUserByPhone

(注意我不知道这是否真的是您让用户服务提供模拟的地方,我只是假设)