A guide on verifying http calls using sinon in an Angular project with Typescript

Our team is in the process of transitioning to TypeScript, but we want to continue using Sinon for our tests.

In the past, we used JavaScript Service Unit Tests like this:

it('should get buyer application status count', function () {
        let httpStub = sandbox.stub(http, 'get').returns({
            then: function () {
                return [];
            }
        });


        let result = service.get();

        httpStub.calledWith(`${constants.APPLICATION_BASE}ApiService/GetMethod`).should.be.true;
    });

The service.get() method triggers an HTTP call to ApiService/GetMethod, and we verify that it is called with the correct URL.

How can we achieve the same functionality in TypeScript with Sinon?

Currently, this is what we are attempting:

it('should get list', () => {
    // Arrange
    let apiServiceStub: SinonStubbedInstance<ApiService>;


    // Act
    apiServiceStub= sinon.createStubInstance(ApiService);

    let result = apiServiceStub.get();

    // Assert -- Here is my question: how can I replicate this line, as it doesn't work currently
    applicationServiceStub.**calledWith**(`${constants.APPLICATION_BASE}ApiService/GetMethod`).should.be.true;
  });

As it stands, the calledWith method only checks against the passed arguments of the method and not how the HTTP call is made. I need a solution that can emulate the behavior seen in the first example - creating an HTTP stub.

Answer №1

Delighted to provide the answer:

describe('testing http stub'), () => {
    let stubbedHttp = fake.stub(TestBed.get(HttpClient), 'patch').returns('Something');

    let output = service.PatchData();

    sandbo.calledWith('YourPatchURL').should.be.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

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

Discover how to set a new default opening page to a component that is not AppComponent

My Angular 6 application initially consisted of a single page, the "search page," with its content in app.component.html and related functions in app.component.ts. However, I was recently tasked with adding a new page, the "Login page." Now, upon loading t ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Vue 3 is unable to detect any alterations made to an object that was created externally to the Vue component

I am working with a class called Character in a file named Character.ts /// This is called when server responds public setAttributeByType(type: StatsTypes, value: number): void { switch (type) { case StatsTypes.STRENGTH: ...

Is it possible to create CSS code in an external file instead of using a style element in Angular2?

Is there a reason why angular2 generates the style code in the head style element instead of an external file? I was hoping to bundle the style code in a bundle.css file and then link it in the HTML head. ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Implementing Bootstrap in Angular 2 using vanilla JavaScript/ES6: A step-by-step guide

Currently, I am in the process of developing an Angular 2 application without TypeScript and facing difficulties with bootstrapping it as I cannot find any relevant examples. My app, which does not include the bootstrap() function, starts off like this: ...

What could be the reason behind the failure of $q.when to resolve when enveloping a third-party promise while utilizing ngMock

Consider the service below: angular.module('app', []) .service('promisey', function ($q) { this.cakey = function () { return $q.when('brownie') } this.fruity = function () { return $q.when(Promise.re ...

Troubleshooting issue with Vue3 - TS Custom State Management

Issue: I am facing a challenge in transferring data between two separate components - the main component and another component. Despite attempting to implement reactive State Management based on Vue documentation, the object's value remains unchanged ...

In Angular 5, when you reset a required form control in a reactive form, the required error message beneath the input field is not cleared

Within my template, there is a form that becomes visible when a button is clicked- <form [formGroup]="person" (ngSubmit)="onSubmitNewPerson()" #formDirective="ngForm"> <mat-form-field> < ...

The error message "Type 'string[]' does not match type 'string' in NestJS" indicates a type mismatch between a string array and a single

I am attempting to download a file by utilizing an external API in NestJS. Here is the snippet of code from my service: import { Injectable } from '@nestjs/common'; import * as fs from "fs"; import * as axios from "axios"; @Injectable() export cl ...

The custom form input in Angular2 is throwing an error because it is trying to access the property 'name' of an

Upon switching to the latest Angular version 2 final, I encountered the following error Uncaught TypeError: Cannot read property 'name' of undefined This is my customized input import { Component, EventEmitter, Provider, forwardRef } from &a ...

What is causing the failure of this polymorphic assignment within a typed observableArray in Knockout?

Consider a scenario where we have a class A and its subclass B. The goal is to assign an array of instances of class B to an array of instances of class A. While this works with normal arrays, the same operation fails when using ko.ObservableArray. import ...

Make sure a Typescript array contains a particular value

Currently, I am in the process of developing a dropdown-style component where the value and options are separate props. My goal is to incorporate Typescript to ensure that the value remains a valid option. Although I could perform this validation at runtim ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Auto-login functionality in Ionic 2 is failing to work properly on Android Nougat within the Ionic development application

I've been working on an Ionic application and have successfully implemented the login and registration functionalities using JWT. The app checks for authentication by validating the token, and if the token is missing or different from the server, the ...

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

Exploring techniques to retrieve data from Json Array in Angular using Firebase documentation

this.currentUser$=this.afs.doc('users/'+this.authState.uid).valueChanges().pipe(); When I include it in my component.html file like this: {{ currentUser$|async|json}} The output I get is as follows: { "photoUrl": "", &qu ...