I have been struggling for a long time with trying to mock one function I want to test. I have been reading the Jest documentation and I'm sure the answer probably is there somewhere but I just can't but the pieces together to make it work. I also couldn't find any previous question that made me solve my issue as many of the ones I looked into seems a bit outdated.
This is the function I'm trying to test (a bit simplified):
export function getOrganizationAdministrationLinks(permissions: RolePermission[], features: FeatureEnum[],
translateService: CustomTranslateService): Array<{ name: string, target: string } | 'divider'> {
const uiLinks = new Array<{ name: string, target: string }>();
const organizationLinks = new Array<{ name: string, target: string }>();
const tradingLinks = new Array<{ name: string, target: string }>();
if (havePermissionsAndFeatures(permissions, features, OrganizationSettingsPermissions.permissions, OrganizationSettingsPermissions.features)) {
uiLinks.push({ name: translateService.get('something'), target: 'interface' });
}
return [uiLinks, organizationLinks, tradingLinks]
.filter(group => group.length > 0)
.flatMap(group => [...group, 'divider' as const])
.slice(0, -1);
The dependency I'm having issues with is the CustomTranslateService
one. It looks like this:
export class CustomTranslateService {
public onLangChange: EventEmitter<LangChangeEvent>;
constructor(private readonly translate: TranslateService,
private readonly userBrowserStateService: UserBrowserStateService) {
this.onLangChange = this.translate.onLangChange;
this.setCulture(this.userBrowserStateService.getCulture());
}
/**
* Returns a translation for the translation key & params.
*/
public get(key: I18nKey): string {
if (typeof key === 'string') {
return this.translate.instant(key);
} else {
return this.translate.instant(key.key, key.params);
}
}
The part I'm struggling with is that when calling getOrganizationAdministrationLinks
which is the function I want to test, I have to pass a CustomTranslateService
. The CustomTranslateService
itself has dependencies and I can't figure out how to mock this. I suspect that I might have to mock it manually but it feels a bit overkill since I just want to mock the return call of the get
method.
I'm only using jest
and jest-preset-angular
packages. I've seen some suggestions of using ts-jest
but I'm not sure if it's needed. Also I'm on Angular 12.0.2 and TypeScript 4.1.3.