#Dependency Injection issue

6 messages · Page 1 of 1 (latest)

rain forum
#
Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument UserRepository at index [0] is available in the RootTestModule context.

I only have one module (users) besides the AppModule. This is happening when I run the unit tests for the users controller. This is my test:

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [UsersService],
    }).compile();

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

  describe('create', () => {
    it('should return the created user', () => {
      const createUserDto: CreateUserDto = {
        username: 'test-user',
        password: 'password123',
      };
      const result = controller.create(createUserDto);
      expect(result).toBe(createUserDto);
    });
  });
});

I'm not sure what's wrong. The app runs fine but it errors out in tests.

cerulean lotus
# rain forum ``` Nest can't resolve dependencies of the UsersService (?). Please make sure th...

Have you tried this way:

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

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UsersController],
      providers: [
         {
            provide: UsersService,
            useValue: {
               create: jest.fn(() => {}),
            }
         }
      ],
    }).compile();

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

  describe('create', () => {
    it('should return the created user', () => {
      const createUserDto: CreateUserDto = {
        username: 'test-user',
        password: 'password123',
      };
      const result = controller.create(createUserDto);
      expect(result).toBe(createUserDto);
    });
  });
});
``` ?
rain forum
#

@cerulean lotus Yeah, I searched the old posts and am now mocking the entire service. However, I'm getting 'result' to be undefined somehow.

#

NVM, fixed. Thanks.

cerulean lotus
#

I don't know if you've already viewed it but I'm attaching this link to a repository: https://github.com/jmcdo29/testing-nestjs, there are many test examples, maybe it can help you during testing so you can take a cue.

rain forum
#

Yeah, I've come across that exact link. Very helpful indeed.