I've been grappling for a while now with trying to simulate a specific function that I need to test. Despite going through the Jest documentation, I haven't been able to piece together the solution. I couldn't find any relevant questions that provided a solution either, as most of them seemed outdated.
Here's the simplified function I'm attempting to test:
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 stumbling block for me is the CustomTranslateService
dependency. It appears 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 issue arises when I try to call the
getOrganizationAdministrationLinks
function for testing, as it requires passing in a CustomTranslateService
. This service itself has dependencies, and I'm struggling to figure out how to mock it. I suspect I may have to manually mock it, but that seems excessive since all I really want to do is mock the return value of the get
method.
I'm only using jest
and jest-preset-angular
packages. There have been suggestions about using ts-jest
, but I'm unsure if it's necessary. Additionally, my environment is Angular 12.0.2 and TypeScript 4.1.3.