Skip to content

Mocking getters #593

@RWOverdijk

Description

@RWOverdijk

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe it

I am mocking some third party api responses perfectly, but need to also mock some local services (nest) which contain getters.

This specific example is a config service which contains:

import { ConfigService } from '@nestjs/config';

@Injectable()
export class MyConfigService implements OnModuleInit {
  constructor(private readonly configService: ConfigService) {}

  get isCli() {
    return this.configService.get<string>('APP_MODE') === 'cli';
  }
}

isCli becomes some mocked object, which means it resolves to true while it should be resolving to false.

Describe the solution you'd like

I'd like to be able to mock the getter. Currently it doesn't allow me to do this. I work around it by doing:

const myLegacyConfigService = unitRef.get(
  MyLegacyConfigService,
);

// @ts-expect-error readonly getter.
myLegacyConfigService['isCli'] = false;

But I'd much rather mock the value without needing a ts-expect-error.

What is the motivation / use case for changing the behavior?

Be more in line with how mocking methods works.

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions