The process of creating Jasmine tests for an Angular 2 Observable

Currently, I am in the process of testing a component that involves calling a service. My goal is to effectively stub or mock the service in order to control its return value and manipulate the component variables within the callback/success function of the subscribe method. Specifically, when my component invokes the getBusinessDetails method in welcomeService, I encounter an issue. I aim to simulate a predefined Boolean value for the isReturning variable and then update the relevant component variables accordingly. However, I am seeing an unexpected outcome where undefined is expected to be true.


public getBusinessDetails(): void {
        this.welcomeService.getBusiness(this.businessId, 2017)
            .subscribe((isReturning) => {
                this.isReturningApplicant = isReturning;
                this.welcomeMessage = this.isReturningApplicant ? 'Welcome Back' : 'Welcome';
            });
    }

TestBed.configureTestingModule({
            declarations: [WelcomeComponent],
            imports: [ReactiveFormsModule],
            providers: [{ provide: SessionService, useValue: sessionServiceStub },
            { provide: WelcomeService, useValue: welcomeServiceStub }]
        });

describe('Gets details', () => {
        beforeEach(() => {
            sessionServiceStub = {
                getSession: function () { return { businessId: 11111, agentId: 11111 } }
            }
            welcomeServiceStub = {
                getBusiness: function () { return { subscribe: () => Observable.of(true) } }
            };
        })

        it('get a returning customer', () => {
            component.ngOnInit();
            expect(component.isReturningApplicant).toBe(true);

        });

    })

Answer №1

Simply have it produce the observable without using subscribe

getBusiness: function () { return Observable.of(true) }

The Observable that is generated still contains the subscribe method

getBusiness().subscribe()

Once getBusiness provides the Observable, you can then switch to calling Observable.subscribe

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

The complete Angular 2 application fails to load when accessed using a custom domain name

I've been struggling for the past few days trying to solve a strange issue. When I try to access my Angular 2 app using a domain name (example.com), it gets stuck on the loading screen. However, if I try accessing the same app without nginx, it loads ...

The error message `Error [ERR_REQUIRE_ESM]: require() of ES Module` is triggered when attempting to call the old

I've been attempting to integrate with the Unsplash API, but I'm encountering an issue. When I try to execute the script using ts-node like this: ts-node unsplash.ts I receive the following error: C:\Users\USER\AppData\Roamin ...

Angular is hindered from updating due to its reliance on TypeScript dependencies

My Ionic info is as follows: Ionic CLI : 6.2.1 (C:\Users\Arashsoft\AppData\Roaming\npm\node_modules\@ionic\cli) Ionic Framework : @ionic/angular 5.0.5 @angular-devkit/build-angular ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

"Enhancing Angular 2 with a robust HTTP retry system

My API uses token-based authentication for security. Once a user successfully signs in, two tokens (access and refresh) are stored in the browser's local storage. The access token contains all the necessary information for server-side authorization an ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

TypeScript generic functions causing incorrect typing issues with nested correlated unions

I am currently working on incorporating a predefined TypeScript configuration that can be dynamically loaded into my application. The configuration is structured as shown below: // Base object types type Config<D> = { fn: ({ option }: { option: D } ...

Having trouble utilizing a custom array of objects in TypeScript and React?

After rendering a Functional Component that retrieves a list of objects, I successfully run a foreach loop with it. However, when I attempt to make http requests with each object to create a new array, something seems off. The formatting appears to be inco ...

Reference loss occurs in Angular Ionic when using @ViewChild

This situation is straightforward I am dealing with a reference in this format @ViewChild('myElement') myElementVar : SomeClass; The element I am referencing appears like this <element #myElement *ngIf="someBoolean"></element> As ...

The constructor for this property 'formGroup' does not have an initializer and is not explicitly assigned a value

Hey there! I am still learning angular and encountering an issue that says "Property 'formGroup' has no initializer and is not definitely assigned in the constructor" even though I have declared formGroup. Not sure why this error is popping up. i ...

Is there a way to streamline this generator without using recursion?

I need to develop a unique value generator that produces values within a specified range. The criteria are: all generated values must be distinct the order of values remains consistent upon each run of the generator each value should be significantly diff ...

Are you looking to refresh the Amplify Redirect URL?

Is there a way to update the redirection URI for Amplify signout in the 'aws-exports' file? What steps should be taken to make this change? Can we simply modify the file directly and then execute 'amplify push'? Update After attempti ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Is there a method to retrieve Mui state classes easily?

One thing I really appreciate is the way to style mui-components with their class names. I'm curious if there's a method to access state classes like Mui-checked using a variable. Let me delve deeper into this: I have a styled component that lo ...

What is the best way to trigger an API call every 10 seconds in Angular 11 based on the status response?

I am in need of a solution to continuously call the API every 10 seconds until a success status is achieved. Once the success status is reached, the API calls should pause for 10 seconds before resuming. Below is the code I am currently using to make the A ...

The error message "Property 'value' is not present on type 'EventTarget & HTMLSelectElement'" indicates that the 'value' property is not recognized on the Event

Here is the code snippet that I am working with: interface IHandleSelection { (value: string): any | void; } interface IPipeChangeEventValueToFunction { (handler: IHandleSelection): (event: React.ChangeEvent<HTMLSelectElement>) => void; ...

Is there a way to store session variables in Angular without the need to make an API call?

I am currently working with a backend in PHP Laravel 5.4, and I am looking for a way to access my session variables in my Angular/Ionic project similar to how I do it in my Blade files using $_SESSION['variable_name']. So far, I have not discove ...

What distinctions exist between creating something in the constructor as opposed to the ngOnInit method in Angular?

I set up a form using a function in the constructor. constructor(private userManagementService: UserManagementService, private fb:FormBuilder) { this.createForm(); } createForm(){ this.signupForm = this.fb.group({ firstName:['&apos ...

Discovering alterations in a component's attribute -Ang8

In my component, there are buttons to set the properties as follows: dataType:String = null fechaI : Date = null fechaF :Date = null checkedList =[] I need to trigger an HTTP request when all properties have values and redo the request if any of them ...