How can I mock this with Jest?

Viewed 24

How can I mock the line?

get base(): CrudController<Parametros> {
  return this;
}
@Controller('parametros')
export class ParametrosController implements CrudController<Parametros>{
  private readonly msg: 'No se permite la operación para el rol del usuario.';
  
  constructor(
    public service: ParametrosService,
    public usuariosService: UsuariosService){}

  get base(): CrudController<Parametros> {
    return this;
  }
}
1 Answers

You did not really provide the module but when you register the controller in the module you can get the reference of the instance so you can spyOn it.

app = await Test.createTestingModule({
    controllers: [ParametrosController],
  }).compile();

const controller = app.get<ParametrosController>(ParametrosController);
const mock = jest.spyOn(controller, 'base', 'get').mockReturnValue({hmm: 123});

expect(controller.base).toEqual({hmm: 123});
expect(mock).toHaveBeenCalled();

spyOne function accepts accessType as a 3rd parameter, so you can pass get when it is a getter.

Related