Error message thrown when attempting to access Navigator InjectionToken in tests: ReferenceError - Navigator is not defined

I have created an abstraction for the Navigator object:

export const NAVIGATOR: InjectionToken<Navigator> = new InjectionToken<Navigator>(
  'An abstraction over window.navigator object',
  {
    factory: () => inject(WINDOW).navigator,
  },
);

And also, an abstraction for the Window object:

import { inject, InjectionToken } from '@angular/core';
import { DOCUMENT } from '@angular/common';

export const WINDOW: InjectionToken<Window> = new InjectionToken<Window>(
  'An abstraction over global window object',
  {
    factory: () => {
      const { defaultView }: any = inject(DOCUMENT);

      if (!defaultView) {
        throw new Error('Window is not available');
      }

      return defaultView;
    },
  },
);

I require these abstractions in order to mock providers for testing classes. However, whenever I inject the Navigator Token into a service like this:

export class MyService {
  constructor(
    @Inject(NAVIGATOR) private navigator: Navigator,
  ) {}
}

And run unit tests, I encounter the following error:

ReferenceError: Navigator is not defined

      3 |   constructor(
    > 4 |     @Inject(NAVIGATOR) private navigator: Navigator,
        |                                           ^
      6 |   ) {}

My tsconfig.ts configuration is as follows:

{
  "compilerOptions": {
    "allowJs": true,
    ...
    }
}

Similarly, my tsconfig.spec.ts looks like this:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    ...
    ]
  }
}

Any suggestions on how to resolve this issue?

Answer №1

If you want to simulate your service, you can do it in the following way:

TestBed.configureTestingModule({
    imports: [...],
    declarations: [...],
    providers: [
        {
            provide: NAVIGATOR,
            useFactory: () => ({
                myMockedMethod: () => {},
            }),
        },
    ],
});

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

A custom Typescript type for immutable values within an object

I am struggling with finding the right data type for my function, where I need to work with static types. I have experimented with Type, interface, class, Record, and others, but none seem to fit perfectly. GEOLOCATIONS is a constant record that maps cou ...

Issue with hydration in Next.js while trying to access the persisted "token" variable in Zustand and triggering a loading spinner

Below is the code snippet from _app.tsx where components/pages are wrapped in a PageWrapper component that handles displaying a loading spinner. export default function App(props: MyAppProps) { const updateJWT = useJWTStore((state) => state.setJWT); ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Ways to retrieve element values within Angular

Here is an example of an element: <li class="someClass">value1<span>value2</span></li> This list element is created using vanilla JavaScript, and a click event is bound to it as demonstrated below: const list = Array.from(documen ...

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

I'm struggling to find the right Typescript syntax for defining a thunk function that returns a value while using React Redux Toolkit

Currently, I am utilizing TypeScript within a React Redux Toolkit project. While attempting to create an Async Thunk action function that is expected to return a boolean value, I found myself struggling with determining the correct TypeScript syntax: expor ...

Endpoint not returning data as expected

I'm facing an issue with my routing module where I have successfully used activatedRoute for multiple other modules but now running into trouble when implementing it in a new singular component. The structure of my routing module is as follows: const ...

Tips on accessing controller scope while testing a directive with isolate scope

Is it correct to write unit tests for a directive with isolate scope and controller, as well as test some functionality within the controller's scope? If so, how can access be gained to the controller scope? angular.module('myApp').dire ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

What are the steps to conduct a vulnerability scan on an Angular/Node application?

I'm in the process of setting up a vulnerability check for my Angular 7/Node project. Can anyone advise on how to effectively run this type of process? Are there any recommended tools available? Initially, I attempted to use the dependency-check-mave ...

Transform an Excel spreadsheet into Json format effortlessly with Kendo's powerful tools

My upload feature allows users to upload an Excel sheet, and the backend API expects the data in JSON format. Here is an example of the expected input: [{ "LineNumber": "1", "Parma": 123, "PartNumber": 234, "Tes ...

Nested component in reactive forms not functioning as expected

I've been experimenting with creating nested reactive form components. Specifically, I'm working on a reusable input component for my app within a reactive form. How can I dynamically communicate with nested components in Reactive forms? Despite ...

Revising input value post model binding

In my scenario, I have a text input that is bound to a model property of type Date: <input type="text" [(ngModel)]="model.DateStart" ngControl="dateStart" id="dateStart" #dateStart /> The value of model.DateStart (which is of type DateTime) looks l ...

displaying an item within a text field

I have an input box created using Angular reactive forms <input type="text" formControlName="OrgName" placeholder="Enter name" maxlength="60"> <p class="fieldRequired" *ngIf="showNameMSg" ...

Error in cypress configuration occurs when a plug is mistakenly defined as an import instead of a const within the cypress.config.ts file

Hello, I am new to using Cypress so please bear with me if this seems like a trivial issue. Below you will find my cypress.config.ts file where I am attempting to integrate the cypress esbuild preprocessor into the configuration. import cypress_esbuild_pre ...

Angular2, RxJS Subject HTTP request - If an error occurs, the request will not be triggered again

Encountering an issue with handling an http error response (specifically a 422 validation error from the backend). After receiving an http error response, unable to trigger the request again by clicking the button. 1) Utilizing a subject property and cal ...

Scrolling to the bottom of an ion-content in Ionic 4

I am currently developing a chat page with Ionic 4 and I'm attempting to implement an automatic scroll feature to the bottom of the page. However, the method I tried using doesn't seem to be working as expected: import { IonContent } from "@ioni ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

"Exploring the dynamic duo: Algolia integration with Angular

I've been following a tutorial on implementing instantsearchjs in my website, which can be found here. Everything is set up correctly and I can query for results in .JSON format from my website. However, I'm having trouble figuring out how to r ...

What is the best way to organize objects based on their timestamps?

I am faced with the task of merging two arrays of objects into a single array based on their timestamps. One array contains exact second timestamps, while the other consists of hourly ranges. My goal is to incorporate the 'humidity' values from t ...