Write test for an Angular async service method

Discussão em 'Angular' iniciado por meji, Setembro 17, 2025.

  1. meji

    meji Guest

    I new to Angular and im having trouble writing unit tests for the following method for a service using jasmine/karma. Please advise?

    Test needs to cover the following: this.httpClient.post was called with a url and this.httpClient.post returns data of type "ISearchResponse"

    export interface ISearchTermResponse {
    search_id: number;
    user_id: string | null;
    search_createdAt?: string;
    search_term?: string;
    search_isUserSearchTerm?: boolean;
    }

    export interface ISearchResponse {
    status: string;
    result: ISearchTermResponse;
    }

    export interface ISearchesResponse {
    status: string;
    response: {
    searches: ISearchTermResponse[];
    user_id: string | null;
    };
    }

    async saveSearchTerm(searchTerm: string, userId: string, baseApiUrl: string) {
    const saveParams = {
    search_term: searchTerm,
    user_id: userId ? userId : null,
    };

    const saveSearchUrl = baseApiUrl + env.apiEndpoints.search.paths.saveSearch;

    return this.httpClient
    .post<ISearchResponse>(saveSearchUrl, saveParams, {
    headers: await this.headersService.getHeaders(),
    })
    .pipe(
    timeout(env.apiEndpoints.aichat.timeout),
    catchError((error) => {
    console.log(
    "There was an error saving search term",
    error,
    searchTerm,
    userId
    );
    return throwError(() => error);
    }),
    finalize(() => {
    //
    })
    );
    }

    Continue reading...

Compartilhe esta Página