#Unit test for controller using a fake database

12 messages · Page 1 of 1 (latest)

cold fractal
#

Hey, I'm trying to write unit tests for my controller but I don't want to use my real databse since I don't want the test to modify it. I have an in memory repository to handle those fake db operations but I don't know how to actually use it on the controller tests:

describe('UserController', () => {
  let userController: UserController;
  let repository: InMemoryUserRepository;

  beforeEach(async () => {
    const user: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [UserService, PrismaUsersRepository],
    })
      .overrideProvider(PrismaUsersRepository)
      .useClass(InMemoryUserRepository)
      .compile();

    userController = user.get<UserController>(UserController);
    repository = new InMemoryUserRepository();
  });

  describe('root', () => {
    it('should return all users', async () => {
      const data = new UserBuilder().makeSimpleUser();

      repository.create(data);

      const { users } = await userController.findUsers('1');

      expect(users).toHaveLength(1);
    });
  });
});
flat kestrel
#

Side question, does your in memory repo not have the same interface as your 'real' repo? They should. What does users return here?

flat kestrel
#

repository = new InMemoryUserRepository();
This should come from the module

#

they are not the same instance right now

cold fractal
#

yeah, solved it doing that haha

#

thanks!

flat kestrel
cold fractal
#

forgot to add await there too

#

hehe

#
describe('UserController', () => {
  let userController: UserController;

  beforeEach(async () => {
    const user: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [UserService, PrismaUsersRepository],
    })
      .overrideProvider(PrismaUsersRepository)
      .useClass(InMemoryUserRepository)
      .compile();

    userController = user.get<UserController>(UserController);
  });

  describe('root', () => {
    it('should return all users', async () => {
      const data = new UserBuilder().makeSimpleUser();

      const { user } = await userController.create(data);

      const response = await userController.findUsers('1');

      expect(response).toMatchObject({ users: [user] });
    });
  });
});