Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service.

This is the content of my component file:

  submitLoginForm() {
    if (this.loginForm.valid) {
      // send a http request to save this data
      this.guestUserService.login(this.loginForm.value).subscribe(
        result => {
          // if (result) {
          if (result['token']) { // The value of result is coming the complete HttpResponse. 
            localStorage.setItem('authToken', result['token']);
            this.router.navigate(['/dashboard']);
          }
        },
        error => {
          console.log('error', error.message);
          this.router.navigate(['/error']);
        }
      );
    } else {
      this.validateAllFields(this.loginForm);
    }
  }

}

Here is the unit test case:

fdescribe('LoginComponent', () => {
    let component: LoginComponent;
    let fixture: ComponentFixture<LoginComponent>;
    let guestUserService: any;
    let guestUserServiceSpy: any;

    beforeEach(async(() => {
        guestUserService = jasmine.createSpyObj('GuestUserService', ['login']);

        TestBed.configureTestingModule({
            declarations: [LoginComponent, ErrorComponent, RegistrationComponent],
            imports: [
                ReactiveFormsModule,
                FormsModule,
                RouterTestingModule,
                HttpClientModule,
                AppRoutingModule,
            ],
            providers: [
                { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
                { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
                { provide: APP_BASE_HREF, useValue: '/' },
                { provide: GuestUserService, useValue: guestUserService }]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(LoginComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

  it('should Successfully Submit Registration Form', async(inject([Router], (router) => {
        guestUserServiceSpy = guestUserService.login.and.returnValue(of(new HttpResponse({ status: 200, body: { result: { token: 'DummyTokenIsSent' } } })));

        spyOn(router, 'navigate');
        spyOn(component, 'submitLoginForm').and.callThrough();

        component.loginForm.controls['username'].setValue('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c0c9dbc6c9c6c1e8dec1dbc0c9c486cbc7c5">[email protected]</a>');
        component.loginForm.controls['password'].setValue('12345678');

        component.submitLoginForm();

        expect(component.submitLoginForm).toHaveBeenCalled();
        expect(component.loginForm.invalid).toBe(false);

        expect(guestUserService).toBeDefined();
        expect(guestUserServiceSpy).toBeDefined();
        expect(guestUserServiceSpy).toHaveBeenCalledTimes(1);
        expect(router.navigate).toHaveBeenCalled();
        expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
    })
    ));

Upon running the test case, the value of the result is as shown in this https://i.sstatic.net/CMof6.png image link.

During testing, an issue was identified where the code did not proceed through the section "if (result['token'])". I'm looking for suggestions on how to access or send the body part of the HTTP response from the unit test case without impacting the component.

Answer №1

Try including HttpClientTestingModule for importing and simulating your http response:

httpMock = injector.get(HttpTestingController);
const request = httpMock.expectOne(`path`);
expect(request.request.method).toBe("POST");
request.flush({dummyResponse:true});

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

Using JQuery to deactivate a button based on a specific select option

Once a user selects and submits an option from the dropdown list of collections in my form, I aim to disable the button so that they cannot submit that same collection again. Although Ajax is functioning properly and successfully disables the button upon s ...

Surveillance software designed to keep tabs on how long visitors remain on external websites

My goal is to increase sign-ups on my website by providing users with a unique JavaScript snippet to add to their own sites. I have two specific questions: 1) If I implement the following code to track visit duration on external websites, how can I ensure ...

Encountered an error while trying to install a package using NPM due to the requirement of 'require-from-string@

Every time I try to install a package (even nodejs), I encounter this issue. Here is what I have tried so far: Uninstalled all dependencies Cleared cache Reinstalled NPM / AngularCli Unfortunately, running any NPM command still results in the same error ...

Issue with arrow function not being invoked in a React TypeScript component's prop inside a function

My parent component holds a useState hook to determine if the mobile Nav is open or closed: const [showMobileMenu,setShowMobileMenu] = useState<boolean>(false);. To close the mobile menu, I created an arrow function and passed it down to a child comp ...

What is the method to verify if a pop-up browser window has completed its loading process?

There is a link on my website that opens a new window. However, sometimes the new window takes so long to load. To prevent users from clicking on the link before the new window finishes loading, I want to disable it until then. I am aware that one way to ...

Guide to utilizing JSDoc within your local project

Objective My goal is to utilize jsdocs with npm in my project. Experience I am new to working with npm and its plugins. Recently, I came across jsdoc and attempted to incorporate it into my project without success. Attempted Solution Initially, I inst ...

What are the two different ways to declare a property?

I am trying to update my interface as shown below interface Student{ Name: String; age: Number; } However, instead of the current structure, I would like it to be like this interface Student{ Name: String; age | DOB: Number | Date; } This means t ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...

Encountered a problem while attempting to create a new project using angular/cli

I'm brand new to npm and Angular 2, and I'm attempting to set up a fresh Angular 2 project using angular/cli. My current setup includes: Node v8.9.3 npm v5.6.0 Windows 10 To start, I executed npm install -g @angular/cli successfully. Next, I n ...

How do I test Pinia by calling one method that in turn calls another method, and checking how many times it has been called

As I embark on my journey with Vue 3 and Pinia, a particular question has been lingering in my mind without a concrete answer thus far. Let's delve into the crux of the matter... Here's an example of the store I am working with: import { ref, co ...

stop automatic resizing of windows

My CSS is written using percentages. I need to maintain the percentages intact. Is there a way to stop the layout from changing when the browser window is resized? I want the percentages to remain unaffected, even when the browser window is being resized ...

Exploring the Document Object Model to locate the adjacent sibling of a parent element

If I need to implement an event that hides the section .dependent-box whenever the element with class .radio-click-hide is clicked, what would be the best approach for traversing the elements to achieve this functionality? I have attempted the following co ...

Tips for assigning a value to a Reactive Form control within Angular 6

I am looking to dynamically set the value of a text box when clicking on a button that is located outside of the form. How can I achieve this? <form [formGroup]='student' (ngSubmit)='click()'> <input type='text' form ...

Executing a function without using the eval() function

I am currently working on a JavaScript code that relies heavily on the eval function. eval(myString) The value of myString is equal to myFunc(arg), and I would like to find a way to call myFunc directly instead of using eval. Unfortunately, I have no co ...

What is the best way to incorporate ng-select within a custom form controller?

I've attempted to create a stackblitz demo to illustrate my issue, but unfortunately, I couldn't make it work properly. Therefore, I'm reaching out for assistance. I have 2 components: Component 1 is a specialized form controller that encap ...

Is it possible for me to utilize jquery and AJAX to invoke a cgi-bin script, and then incorporate a message event to manage Server Sent Event?

I have a cgi-bin program that runs for a long time (3-15 minutes) and I am looking to invoke it using AJAX. While the program is running, I want to receive Server Sent Event data from it and display it on my web page. It's like having a progress monit ...

Preventing unauthorized access to files in ExpressJS public directories

Is there a way to conceal files served by the Node server? Despite my attempts to redirect certain files and directories, Express 4.X does not seem to cooperate. I have also experimented with sending 4XX HTTP responses when specific files are requested, bu ...

Understanding how to activate a React navbar button is essential for creating a seamless user

How can I make my sidebar button change color when I navigate to the page it links to? ...

The canvas animation displays a sequence of previous frames

My challenge lies in rotating an object on the canvas, as all previous frames continue to be displayed. I suspect the issue is related to this particular line of code: setTimeout(this.rotate.bind(this), 1000 / 10); Is there a way to have only the current ...

trouble with file paths in deno

I was attempting to use prefixes for my imports like in the example below: "paths": { "~/*": ["../../libs/*"], "@/*": ["./*"] } However, I keep encountering an error message say ...