Testing Angular 11 methods using Jest unit tests within a .then block

Currently, I am running jest unit tests in Angular 11 and facing an issue while testing methods within the .then method.
It seems like the test methods are not being executed at the expect method.

I need guidance on how to structure the test code to ensure it waits until the .then method completes.
My goal is to verify if the idToken is correctly set in the localStorage within the .then method.

Versions:

// package.json

"dependencies": {
    // List of dependencies
},
// Dev Dependencies section with versions specified

Component Method:

// my-component.ts

signIn() {
   // Implementation details for the signIn method
}

Test Code:

// my-component.spec.ts

describe('MyComponent', () => {
    // Test setup details
});

Run Command:

$ jest --runInBand --watch

Result:

  ● MyComponent › script › fetchIdToken › ok

    Explanation of the encountered issue and result

      // Details regarding the error or expected behavior

Answer №1

To simulate local storage in all test scenarios, it is recommended to set it up within the beforeEach() function.

let customLocalStorage;

beforeEach(() => {
  customLocalStorage = {};

  spyOn(window.Storage.prototype, 'getItem').and.callFake((key) =>
    key in customLocalStorage ? customLocalStorage[key] : null
  );
});

Alternatively,

let customLocalStorage;

beforeEach(() => {
  customLocalStorage = {};

  spyOn(window.localStorage, 'getItem').and.callFake((key) =>
    key in customLocalStorage ? customLocalStorage[key] : null
  );
});

Answer №2

My suggestion would be to adjust the mocking of the token service in this manner:

    userServiceSpy.fetchIdToken.mockImplementation(() => 
      new Promise((resolve) => resolve('newToken'))
    );

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

Troubleshooting: Issues with Angular 2's default routing system

My Angular 4 app's default route isn't functioning properly. Could it be conflicting with my express routes? Interestingly, the wildcard route seems to be working fine. I'm puzzled as to what the issue might be. Here are my Angular routes: ...

Loop through a FormArray containing FormGroups

I'm struggling with the functionality of my form array containing form groups. My goal is to loop through the form array and display the input fields within each form group. However, when I use addExercise(), the new form group that I add to the arra ...

Determining the parameter type of an overloaded callback: A comprehensive guide

I am currently working on creating a type-safe callback function in TypeScript with a Node.js style. My goal is to define the err parameter as an Error if it exists, or the data parameter as T if not. When I utilize the following code: export interface S ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

What is the best approach for retrieving an image efficiently with Angular HttpClient?

My backend currently sends back an image in response. When I access this backend through a browser, the image is displayed without any issues. The response type being received is 'image/jpeg'. Now, I am exploring different methods to fetch this ...

Best practice in Angular 2: The difference between binding an object as a whole versus binding its individual

What is the best approach for a child component when dealing with object properties and change events? Example 1 <parent-component> <child-component [exampleInput]="object.val" (valueChanged)="updateObjectValue($event)"> ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

Angular 5 custom dropdown menu

Currently, I am utilizing the ng-select component available at https://github.com/ng-select/ng-select. However, there are instances where the content of the dropdown is too lengthy. To address this issue, I have decided to shorten the string in the dropd ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

Creating dynamic meta tags in Angular using server side rendering

I have developed an Angular application with Server-Side Rendering. Before deploying the final result to Azure SWA, I utilize the prerender command. One of the components in my application is a blog post component, and here is the code snippet: import { C ...

TS fails to recognize any additional properties added to the constant object

When working on a function that should return an object with properties 'a' and 'b', I am defining the object first and then adding values to it later: const result = {}; result.a = 1; result.b = 2; return result; However, TypeScript i ...

The parameter must be of type 'string', but you are attempting to assign a 'Promise<any>'

Starting a React App requires fetching the user's information from localStorage and initiating a socket connection with the server based on the user's id. However, when trying to pass the user's id to the socket function, TypeScript throws ...

Unlocking the power of asynchronous methods within the useEffect() hook

When attempting to fetch an API within a useEffect(), I encountered the following error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Here is the code snippet that caused the error: -API being fetched: ex ...

Utilizing Nginx to route to various locations with distinct root paths in an Angular server-side rendered build

My website is up and running on the server, hosted at http://example.com. It was built using Angular and I deployed the dist folder containing the code to /opt/example_web/dist/browser on the server. The site is redirecting and loading successfully. I als ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...

The type of 'username' cannot be determined without specifying the reference to '@angular/forms/forms' in the node modules

I'm encountering an issue with my application: forgot-password.component.ts(44,7): error TS2742: The inferred type of 'username' cannot be named without a reference to '.../node_modules/@angular/forms/forms'. This is likely not po ...

Struggling to set up a Jest testing module for a NestJs service. Encountering an issue where Nest is unable to resolve dependencies of the UsersService, specifically the Config

Greetings, fellow developers! I am excited to ask my first set of questions on stackoverflow :) Currently, I am working on a test/learning application to enhance my skills in NestJS and Vue. During the implementation of server-side unit tests using Jest, ...

Implementing Entity addition to a Data Source post initialization in TypeORM

The original entity is defined as shown below: import { Entity, PrimaryGeneratedColumn} from "typeorm" @Entity() export class Product { @PrimaryGeneratedColumn() id: number The DataSource is initialized with the following code: import ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...