0
votes

Trying to test a class that uses @Inject() to inject its dependencies.

users.controller.ts

import { Controller, HttpCode, Body, Post, Inject, Get, Param } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { UploadPhoto } from './usecase/upload-photo.usecase';
import { UploadPhotoReqDto } from './dto/upload-photo.req.dto';
import { Document } from 'dynamoose/dist/Document';
import { DynamooseModel } from '../dynamoose/dynamoose-model.interface';
import { InjectModel } from '../dynamoose/common/dynamoose.decorator';

@ApiTags('Users')
@Controller('users')
export class UsersController {
    constructor(
        private readonly uploadPhoto: UploadPhoto,
        @Inject('UserModel') private readonly UserModel: DynamooseModel<Document>
    ) {}

    @Post('/profile/upload_photo')
    @HttpCode(200)
    async postUploadPhoto(@Body() requestBody: UploadPhotoReqDto): Promise<string> {
        const { mime, image } = requestBody;
        const image_url = await this.uploadPhoto.start({ mime, image });
        return image_url;
    }
}

This is my test class.

users.controller.spec.ts

import { Test, TestingModule } from '@nestjs/testing';
import { UploadPhoto } from './usecase/upload-photo.usecase';
import { UsersController } from './users.controller';

const BaseUseCaseMock = {
    start: () => {
        console.log('Starting BaseUseCaseMock');
    },
};

describe('UsersController', () => {
    let controller: UsersController;

    beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [UsersController],
            providers: [
                UploadPhoto,
                {
                    provide: 'UserModel',
                    useValue: {},
                },
            ],
        })
            .overrideProvider(UploadPhoto)
            .useValue(BaseUseCaseMock)
            .compile();

        controller = module.get<UsersController>(UsersController);
    });

    it('Should_BeDefined', () => {
        expect(controller).toBeDefined();
    });
});

enter image description here

All I'm checking for the time being is if the UsersController got instantiated properly. Is this the correct use for the NestJS custom providers?

Any ideas on why this is not working?

1

1 Answers

1
votes

After discussing on Discord, the issue was in the users.service.spec.ts file having the same setup without the mocked dependencies. The above test is actually fine.