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

Time:04-15

I'm trying to create a jest test for the below method. And I got errors for two scenarios.

So basically in checkKioskUserPhone method,

  1. Find the user by the phone number( commonService.findKioskUserByPhone)

  2. In findKioskUserByPhone method, we are gonna find the user by the phone number and send error messages if it's unregistered or already registered.

  3. And then return user.

  4. (back to checkKioskUserPhone) if the user doesn't have auth code and pin number we are gonna send him/her auth code and return jwt, and etc.

    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;
    }

Jest code

        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 Error screenshot

enter image description here

enter image description here

CodePudding user response:

you're overriding the findKioskUserByPhone method to just return null:

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

so findKioskUserByPhone simply is never running, a mock function is just returning null, and is thus never throwing the error you expect. instead, here:

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

user is getting set to null and here:

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

you're trying access some authCode property of null, which throws the TypeError you're getting.

you probably meant to override the findOne method on the user service:

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

so the error you want will actually throw in findKioskUserByPhone

(note I don't know if this is actually where you have the user service to provide the mock, I'm just assuming)

  • Related