Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function.

Component

ngOnInit() {
    // Logging out when reaching login screen for login purposes
    this.authService.logout();
  }

authService

logout() {
    // Removing logged in user from localStorage
    localStorage.removeItem('currentUser');
  }

TEST

fit('ngOnInit should log out user stored in localStorage', () => {
    // Example data stored as token
    localStorage.setItem('token', 'someUserToken');

    component.ngOnInit();

    expect(localStorage.getItem('token')).toEqual('{}');
});

Is there a method to accomplish this?

Answer №1

When it comes to unit testing, the focus should always be on the specific functionality being tested.

For instance, there is no need to verify if local storage gets cleared in your component's test. That task falls under the responsibility of the authentication service that your component interacts with.

Instead, make sure to verify that the correct method is getting called as expected.

it('ngOnInit should call auth.logout', () => {
    spyOn(component['authService'], 'logout');

    component.ngOnInit();

    expect(component['authService'].logout).toHaveBeenCalled();
});

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

Infinite loop readiness with JQuery

My current project involves preloading images and seamlessly fading them in once they are fully loaded using JQuery. To achieve this, I attempted to create an invisible image tag where the images would load before setting the source back to the original im ...

Guide to enabling picklist editing in the specified component within an Angular application

Currently utilizing the p-picklist component and looking to customize the displayed data in the target list span. You can find the source code at: Is there a way to enable editing of the product name within the target list? <p-pickList [source]=&quo ...

Protected Node.js API paths

Recently, I was developing a login with OTP feature for my app. The front-end is being built using Angular and the back-end on ExpressJs. However, I have been struggling to find a way to secure the API. Every time I test the API using Postman, it works per ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Oops! Only one request should be open, but it seems there is one too many

I'm encountering an issue while trying to run HTTP unit test cases. My Angular version is 5. Can someone help me with resolving this? Here is the code snippet for a basic GET request: import { TestBed } from '@angular/core/testing'; import ...

Help me figure out how to independently toggle submenus on my navbar by utilizing the Vue.js composition API

I am currently working on developing a navbar using the Vue.js composition API. My primary objective is to toggle the submenus when a user clicks on them. However, since I am iterating through an object to display the submenus, I am faced with the challeng ...

Create a unique custom design for your Mapbox GL control

When developing the website, we utilized Angular 8, Typescript, and SCSS. We are using mgl-map to display a map, and I wanted to create a custom control for it with unique styles. I added the custom control to the map using: const centerOnCoordinatesC ...

Error encountered in AppModule: ComponentFactoryResolver provider not found in StaticInjector

My rails 5.2.0 webpacker app is up and running smoothly, incorporating a basic angularjs app booted via the angular AppModule using UpgradeModule.bootstrap function. Prior to transitioning into a hybrid app, I made sure that the angular app was functionin ...

The issue of the window.open method malfunctioning on Internet Explorer 9

Struggling to make it work in IE9: Note: I forgot to mention that $variable is coming from a $_GET request based on a drop down menu selection. I am currently offline, <a href="#" onclick="window.open('https://domain.com/contact-form?chatq=& ...

Error Message in Angular2 and ASP.NET: 'Window object is not defined'

As a relatively new Angular2 developer and a complete novice at integrating it into an ASP.NET Web Application, I encountered a peculiar error while attempting to build in debug mode within my Angular2 ASP.NET web application. Surprisingly, the same error ...

The error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

How come the "colspan" attribute is not functioning properly in my table?

Check out the simple table form I created on jsfiddle. Here is the code snippet: <table> <tr> <td class="field_label">name</td> <td>*</td> <td> <input type="text"> ...

Preserve the Browser Scroll Position when navigating to another page

Currently tackling a challenge with JS, JQuery, and PHP where I'm attempting to resolve an infinite scroll issue. The specific problem arises when scrolling down the page extensively while loading more pages via ajax, then navigating to a different pa ...

What are the methods for determining if a Triangle intersects a Box3?

Is there a built-in function in THREE.js to determine if a THREE.Triangle overlaps with a THREE.Box3 object? If not, what approach can be taken to achieve this? ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

What is the best way to toggle the visibility of multiple column groups in Ag-Grid community using dynamic

I am seeking to replicate a basic version of the sidebar found in Ag-Grid Enterprise. The goal is to use JavaScript to gather all column groups within a grid and then provide a checkbox for each group to toggle visibility. While I am aware that individual ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

Integrate predictive text suggestions in JavaServer Pages for efficient form filling

After some research, I have managed to solve the issue I was facing. On my jsp page, I have three text boxes. When I enter data into the first text box, it triggers a call to get.jsp to fetch data from the database and populate the second text box. However ...

Having difficulty understanding why the Javascript regex is not functioning as expected

Can you help me validate user input to ensure it is a positive currency value in the correct format? Examples of valid formats include: 0.5, 0.55, 5 (please note this one), 5.5, 5.55, 55, etc. This is the code I am currently using: if ($("#gross").val() ...