Testing Angular components with Jest's mocking capabilities

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.

Answer №1

Here is a simple test showcasing the solution I was looking to achieve:

    it('getOrganizationAdministrationLinks should correctly return name and target with rolePermissions and features', () => {
    const expected = [{
        name: 'overruns',
        target: 'interface'
    }];

    const translateService: Partial<CustomTranslateService> = { get: () => 'overruns' } ;
    const actual = getOrganizationAdministrationLinks(rolePermissions, features, translateService as CustomTranslateService);

    expect(actual).toEqual(expected);
});

A big thank you to @jonrsharpe for the assistance and provided resources!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

Supertest and Jest do not allow for sending JSON payloads between requests

Below is the test function I have written: describe("Test to Create a Problem", () => { describe("Create a problem with valid input data", () => { it("Should successfully create a problem", async () => { const ProblemData = { ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

Tips for creating case-insensitive query parameter values

Can someone help me troubleshoot why my endpoint for a GET method to /book with a query parameter named name is not returning the correct book title? When the name parameter is 'scott' or 'SCOTT,' it should return "Cracking the Coding I ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

When iterating through a list of strings using ngFor, I am unable to directly access or manipulate the individual items

Within my model, I have a list of strings. <span *ngFor="let item of model; let i = index"> <input #inputField type="text" [name]="name + '_' + i" [(ngModel)]="item" /> </span> The code snippet ab ...

The outcome of the .then function is not defined following another .then function

I am struggling with handling async requests in Angular within Ionic4. I have successfully loaded a .json file and saved it into an array, but when trying to edit the array within a loop, my promise resolves before the loop finishes. As a newcomer to Angul ...

Angular 5 Observables: delivering results upon completion

Looking for assistance with Angular 5 Observables. I am trying to simplify the controller by avoiding the need for it to subscribe to the observable. Instead, I want all the complexity to be handled in the service, which will then easily pass the results/ ...

AngularJS is encountering issues with dependency injections when using WebStorm and TypeScript

A TypeScript AngularJS component: class MyComponentCtrl { static $inject = ['MyService']; constructor(private MyService) { MyService.testfn(55); // No error in typescript } } class MyComponent implements ng.IComponentOptions { ...

Experiencing a 404 error while attempting to revoke access token using Google OAuth2 revoke endpoint

Using angularx-social-login for user authentication via Google. The token retrieval process looks like this: https://accounts.google.com/o/oauth2/iframerpc?action=issueToken&response_type=token%20id_token&login_hint=LOGIN_HINT&client_id=CLIEN ...

Share your Angular Elements web component as an npm module

Is there a way to package an Angular app as an npm module, especially when it is wrapped as a web component using Angular Elements? I'm interested in seamlessly importing the web component into another application through npm, rather than manually inc ...

When utilizing a Private Signed URL or Public URL from AWS S3, the Model Viewer for web fails to display the View in AR button

I integrated ModelViewer 1.9.2 by Google into my Angular project to display 3D models with surface detection for object augmentation. Initially, I successfully augmented 3D models from the application's assets. However, I'm facing issues when try ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Creating dynamic form groups in Angular 4

I am currently working on a dynamic form group and I am facing a particular challenge. https://i.sstatic.net/m20IO.png Whenever I click on "add more," it should add 2 dynamic fields. Here is the function I am using: onAddSurgeries(){ const control = ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Is it considered best practice to include try/catch blocks within the subscribe function in RxJs?

Imagine we have an Angular 2 application. There is a service method that returns data using post(), with a catch() statement to handle any errors. In the component, we are subscribing to the Observable's data: .subscribe( ()=> { ...