Angular 2: Creating a Jasmine test case for accessing the query parameters in activateRoute.snapshot

Currently, I am extracting values from the URL using ActiveRoute in my Angular project.

http://localhost:4200/project-test/#/add?orderId=156&customerNumber=431

In order to retrieve these values, I have implemented a separate component with an ngOnInit() method as shown below:

Snippet:


...
constructor(private activatedRoute: ActivatedRoute,
          public sanitizer: DomSanitizer,
          private customerAPIService : CustomerAPIService) {}

ngOnInit() {

   this.orderId = this.activatedRoute.snapshot.queryParams["orderId"];
   ...
}

Test case:


import { TestBed } from '@angular/core/testing';
import { CreateCustomer } from './create-customer.component';
import { ActivatedRoute } from '@angular/router';
import { CustomerAPIService } from "app/repackaging/service/customer.api.service";

describe('CreateCustomer', () => {
  let component;

  let mockActiveRoute;
  let mockCustomerAPIService;
  let mockQueryParamMap;

  beforeEach(() => {

     mockQueryParamMap = jasmine.createSpyObj('mockQueryParamMap', ['queryParams']);
     mockActiveRoute = {queryParamMap: mockQueryParamMap};

    TestBed.configureTestingModule({
        providers : [
           {
              provide: ActivatedRoute,
              useFactory: () => mockActiveRoute
           },
           {
              provide: CustomerAPIService,
              userFactory: () => mockCustomerAPIService
           }
      ],
      declarations :[
          CreateCustomer
      ]
    });

        component = TestBed.createComponent(CreateCustomer).componentInstance;
    });

    it('should run ngOninit function', function () {
       component.ngOnInit();

       ...

    });
});

I encountered an error while writing a test which states:

TypeError: undefined is not an object (evaluating 'this.activatedRoute.snapshot.queryParams') in http://localhost:9876/_karma_webpack_/main.bundle.js (line 350)

Answer №1

Expanding on @peeskillet's response.

I made a silly error by mistakenly mocking queryParamMap instead of snapshot.queryparams.

http://localhost:4200/project-test/#/add?order=156&customerNumber=431

Here is the solution to simulate activeroutes.snapshot.queryparams["order"].

 let orderId;
 let customerNumber;

 let mockActiveRoute;
 ...

 beforeEach(() => {
    ...

    mockActiveRoute = {
      snapshot: {
        queryParams: {
          order: orderId,
          customerNumber: customerNumber
        }
      }
   };
});

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

Guide to unit testing a button inside an ngFor loop

I am dealing with a scenario where I have a button inside a navigation section that is generated by iterating over a list. <nav *ngFor="let test of getTests(); let last = last"> <button (click)="clickFunction() ></button> </nav> ...

I need guidance on retrieving items from the useRouter() hook when utilizing Next.js with the App Router approach

This code snippet demonstrates how to use Pages Router in React import { useRouter } from "next/router"; import React from "react"; function ShowroomListings({}) { const router = useRouter(); const { listingId } = router.query as ...

What is the best way to arrange and manage assets?

I created a component with an image in it. The current file structure is like this: https://i.sstatic.net/hkZWG.png Now, my query is whether placing the assets folder inside the web folder is the right choice or not? UPDATE This is what I tried: impor ...

How to determine the return type based on the quantity of arguments passed to a rest parameter function

Is there a way to create an arrow function using rest parameters that can return different types based on the number of arguments passed? For example, I am looking to implement a safeId() function with the following return type variations: safeId() // () ...

I am encountering difficulties installing Angular CLI due to error messages. Can you please provide me with a solution

Error encountered while running 'npm install -g @angular/cli': npm ERR! code ENOENT npm ERR! syscall mkdir npm ERR! path C:\Windows\system32'C:\Users\User\AppData\Roaming\npm' npm ERR! errno -4058 npm ...

Display a nested component post initialization in Angular

<ng-container *ngIf="isTrue; else notTrue"> <app-child [property1]="value" [property2]="value" [property3]="value" (function1)="func($event)" ></app-child> </ng-container> <ng-t ...

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...

"Ensure Playwright refreshes the page automatically following navigation when a specific status code is

I find myself in a dilemma where I require my functional browser tests to verify the status code of each page response, and if a 503 error is encountered, try to reload the page a certain number of times before declaring failure. Even though I have experi ...

Combining Filter Subject with RxJS for Text Filtering in Angular Material Table with HTTP Results

I'm attempting to implement the example of Angular Material Text Filtering by using the data obtained from an http get request. export class MyDtoDataSource extends DataSource<IMyDto> { private _filterChange = new BehaviorSubject('&a ...

Entering the appropriate value into an object's property accurately

I am currently facing an issue with typing the value needed to be inserted into an object's property. Please refer below. interface SliceStateType { TrptLimit: number; TrptOffset: number; someString: string; someBool:boolean; } inter ...

Using the -t or --testNamePattern in Jest will execute all tests

Currently, I have set up my testing framework using jest and ts-jest based on the guidelines provided by the ts-jest documentation. When I execute the command yarn test --listTests, I can identify the specific test file I intend to run: processNewUser.ts ...

Exploring the power of Angular's ViewChildren to iterate through QueryList items

My ngFor loop includes child components: @ViewChildren(SingleMultiSelectionComponent) singleMultiSelections: QueryList<SingleMultiSelectionComponent>; I am attempting to iterate through this QueryList: console.log(this.singleMultiSelections); // 1 i ...

Establish a prototype attribute

From what I understand, TypeScript does not make a distinction between prototype properties and instance properties. Additionally, there is no built-in detection for Object.defineProperty on the prototype, which is unlike a feature for typechecking JavaScr ...

The addition of types/cors in Express Typescript causes my POSTMAN request to hang indefinitely

I am experiencing an issue with my React web app and Express TypeScript backend. Previously, my POST request was functioning well, but now it seems to hang indefinitely on Postman without returning any errors. issueController.ts import { RequestHandler } ...

Ways to resolve the issue of 'message' property lacking an initializer in TypeScript without suppressing errors

Currently, in the process of using TypeScript and Sequelize to create a model within Node.js. import { Table, Column, Model, AllowNull } from 'sequelize-typescript'; @Table class Person extends Model { @Column @AllowNull(false) name: strin ...

Enhance Your MUI React Component with Custom Styles and ThemeProvider Integration

Currently, I am delving into the world of MUI components within a React environment. Specifically, I am utilizing MUI 5 and React 17. These MUI components are sourced from a third-party library, resulting in limited direct access. My current goal is to rev ...

The error message "No provider found for MatSidenavContainer within mat-sidenav-content" is being

app.component.html <mat-side-nav-container> <mat-sidenav #sidenav> <mat-nav-list> <a mat-list-item [routerLink]="'/accounts'"> Accounts </a> <a mat-list-item [routerLink]="&ap ...

Connect AngularFire to a specific object

I'm facing an issue with my Users.class where I need it to automatically map or bind after fetching data from Firebase. I've been trying to search for the right term but haven't found any information yet. import { Component, OnInit } from & ...

Verify if the reactive form retains its original values

In my Angular 6 project, I have a reactive form with numerous fields including dropdowns and number inputs. Some of these fields start with empty values while others default to true. Users are allowed to select any combination of fields, making it impossi ...

The type 'Observable<void | AuthError>' cannot be assigned to 'Observable<Action>'

I am encountering an error that reads: error TS2322: Type 'Observable<void | AuthError>' is not assignable to type 'Observable<Action>'. Type 'void | AuthError' is not assignable to type 'Action'. Type &a ...