Angular 5 Service Unit Testing for UPDATE Function

Currently, I am implementing a stepper feature with back, step, next steps. On the last step, when the user clicks 'done,' I need to call a service to update user data. While I have successfully tested the backStep() and nextStep() methods, I now want to test the updateAdmin() method which updates a boolean value. Below is the relevant code snippet:

P.S: How can I effectively test a service that updates data and returns a response?

Controller:

backStep(step: number) {
this.currentStep = --step;
this.currentSlide.emit(this.currentStep);
}

nextStep(step: number) {
if (++step <= this.totalSteps.length) {
  this.currentStep = step;
  this.currentSlide.emit(this.currentStep);
} else {
  this.updateAdmin();
 }
}

updateAdmin() {
  const body = {
   is_admin: true
  }

this.adminService.updateAdmin(user_id, body).subscribe(
  (response) => {
    console.log(response);
   }
 );
}

Unit Tests

it('backStep() should decrement current step', () => {
  comp.backStep(2);
  expect(comp.currentStep).toEqual(1);
});

it('nextStep() should increment current step', () => {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) => start + i);
  comp.nextStep(1);
  expect(comp.currentStep).toEqual(2);
 });

it('Should call updateAdmin method and test mock service', () => {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) => start + i);
  comp.nextStep(4);
//when steps reached to max limit (4) I need to call a mock service which should update a field and return response, here I dont know how to test updateAdmin() method.
  });
});

Thank you in advance.

Answer №1

Although I may not be up to date on the latest version of Angular, I am familiar with using spyOn in Angularjs to address similar issues. I suggest utilizing spyOn to ensure that the method is properly invoked. It is recommended to conduct testing on the service (adminService) in a separate specs file.

    spyOn(comp, 'updateAdmin');
    ...
    ...
    expect(comp.updateAdmin).toHaveBeenCalled();

Another approach is to utilize spyOn to mock the response of updateAdmin in order to simulate both a successful and unsuccessful response.

spyOn(comp,'updateAdmin').and.callFake(function(){
  var deferred = $q.defer();
  deferred.resolve('WANTED RESPONSE');
  return deferred.promise;
});

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

Conceal location labels in maps provided by tilehosting.com

I am currently in the initial stages of developing a maps web application and I want to incorporate maps from tilehosting.com along with the leaflet library (leafletjs.com). Overall, it seems to be working fine, but I'm struggling with hiding the def ...

How to access the ID value from the URL within a different component that was passed as a prop in

I have a scenario where I am building a reusable component with two child components in the following flow: Child Component 1 -> Parent Component -> Super Parent Main Component In the child component, I define a prop called 'url' which is ...

Encountering a 415 Error while making an ajax call using formData

I am attempting to make an ajax call with formData that includes a list of image files and some strings. However, the call is not successful and I am receiving error 415. Here is the code: var file = picChooser.files[0]; var jobExecutionImagesContext = n ...

Is it possible to deactivate the onclick event following a successful ajax request?

I am looking to disable the onclick event after a successful ajax request. <div class="report_button" id="report_button" title="Reportthis" style="width:65px;height:15px;" onclick="reported_text(user_id,lead_id);">Report</div> This is the div ...

When working with a JavaScript array of class objects, it may appear as though the array is empty when it

Currently puzzled by the behavior of this array. Despite my efforts to find an answer, I haven't had any luck so far. I initialize var allMenuItems = []; at the top and then in getMenuItems(), I push multiple new class objects. However, when I call co ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

TypeScript asserts that the Function is not callable

There seems to be an issue with TypeScript not recognizing that a function of type Function is not callable. type Constructable = { new(...args: any[]): any } function isClass(func: any) { return ( typeof func === 'function' && ...

Using .on('mouseover', d => ..) does not yield the same `d` value as using .attr('foo', d => ..) in D3.js

I'm facing an issue with a mouseover tooltip in Observable that seems to fail when I transfer it to a Grafana plugin using React, D3, and Typescript. The technique I followed can be found in this article: Link to Article To simplify the code and deb ...

Encountered an error: Uncaught TypeError - Unable to access property 'active' as it is undefined within React code

<script type="text/babel"> class Frame extends React.Component{ render(){ return ( <div> <h2 className="os-animation" dat ...

What is the best way to produce a random integer within the range of 0 and 2

Here is the code snippet: var i = prompt('Please choose Rock, Paper or Scissors:'); var b = ['Rock', 'Paper', 'Scissors']; Now, I need help in generating a random number between 0-2. My initial idea was to do t ...

Ways to implement StackNavigator along with Redux?

Is there anyone who can assist me in integrating StackNavigator and Redux? It seems straightforward, but I'm encountering issues. index.ios.js import React from 'react' import { AppRegistry } from 'react-native' import { Provi ...

Customize your markers on Google Maps

I have integrated Markerclusterer with Google Maps in a similar way to the example provided. Here is my code snippet: var map = new google.maps.Map(document.getElementById("map"), options); var markers = []; for (var i = 0; i < 100; i++) { var latLn ...

Struggling with extracting an array of objects from a JSON file and accessing individual attributes within each object?

As a newcomer to Typescript, I am eager to work with JSON and access its objects and attributes. However, I am encountering difficulties in achieving this. I have attempted using functions like 'for of' and 'for in', but unfortunately, ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

What are the steps to expand the express object with TypeScript?

I am facing an issue where, after compiling a typescript project, the express import import {Request, Response} is not showing up. I am now attempting to use require, but I am unsure of how to extend the express object and utilize req and res. Any assistan ...

Is it possible to retrieve the width value when using layout=fill in next/image?

<Image alt="image_example" src="/image_example.png" layout="fill" objectFit="none" /> <Test width={?} height={?}/> I developed a straightforward component using next/image. I am interest ...

In Typescript, encountering a member of a union type with an incompatible signature while utilizing the find method on an array of

I need to verify if a specific value exists within an array of objects. The structure of my array is as follows: [ 0: { id: 'unique_obj_id', item: { id: 'unique_item_id', ... }, ... }, 1: {...} ] The objects in the ar ...

React-select: issue with maintaining selected option on input

Hello everyone, I am new to React and seeking some assistance in reviewing my code. I have a component called Bucket that contains multiple challenges as separate components. Here is a simplified version of the code: class CLL_Bucket extends Component { ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...