Unit testing in Angular 2+ involves testing a directive that has been provided with an injected window object

Currently, I am faced with the challenge of creating a test for a directive that requires a window object to be passed into its constructor.

This is the code snippet for the directive:

 import { Directive, ElementRef, Input, OnChanges, OnDestroy, OnInit } from                                             
    '@angular/core';
    import { Inject } from '@angular/core';
    import { Observable, Subscription } from 'rxjs/Rx';


    @Directive({
        selector: '[appFixToViewport]'
    })
    export class FixToViewportDirective implements OnChanges, OnDestroy, OnInit {
    @Input('appFixToViewport') appFixToViewport: boolean;

    // other necessary input initialization
    
    private windowResize$: Subscription;

    constructor(private element: ElementRef,
                @Inject('$window') private $window: any) {}

    // various lifecycle hooks and methods implementation

Whenever I attempt to set up a test component in which this directive is used within the template, I encounter an error related to injections. Here is the test specification file:

import {Component, ElementRef, DebugElement} from '@angular/core';
// additional imports

// Component setup
@Component({
    selector: 'app-test-fixtoviewport',
    template:'<div appFixToViewport="isOpenFlag" ></div>'
    })
class TestFixToViewPort {}

describe('Directive: FixToViewportDirective',()=>{
    let component :TestFixToViewPort
    let fixture : ComponentFixture<TestFixToViewPort>;
    let inputEl: DebugElement;
    const $window= Window;

    beforeEach((()=>{

        TestBed.configureTestingModule({
            declarations: [
                TestFixToViewPort,
                FixToViewportDirective
            ]});

             fixture = TestBed.createComponent(TestFixToViewPort);
             component= fixture.componentInstance;
             inputEl= fixture.debugElement.query(By.css('div'));
        }));
    it('should have a defined component', () => {
        expect(component).toBeDefined();
    });
    })

Additionally, here is the error trace encountered:

Error Trace:

    × should have a defined component
        Error at injectionError 
        Expected undefined to be defined.
            - Additional details of the error stack -

Chrome 59.0.3071 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (1.053 secs / 0.076 secs)

Can anyone provide guidance on how to correctly inject the required window object into the directive during testing?

Answer №1

tag, it is recommended to include ElementRef in your test module:
 TestBed.configureTestingModule({
            declarations: [
                TestFixToViewPort,
                FixToViewportDirective
            ],
            imports: [ ElementRef ]
});

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

Rearranging lists in JHipster: What is the best way to do it?

Seeking advice and guidance on implementing a drag-and-drop reorderable list in JHipster 6.7.1. To illustrate, picture creating a custom ordered list of objects where users can add, remove, and rearrange items. For instance, wanting to move [Epsilon] betw ...

"Prisma vs. Supabase: A Comparison of Image Uploading

I am encountering an issue with adding image URLs to the Prisma database. I have successfully uploaded multiple images from an input file to Supabase storage, but when I try to add their URLs to the database, I receive an error regarding property compatibi ...

Is there a way to access the value of a variable from a .ts file within a .scss file?

Utilizing a css-only pie chart, I am looking to incorporate the value of this.performance in my scss to determine the percentage. How can I manipulate my scss file from .ts file? Below is a snippet of my css code in scss: $configs: ( chart-one: ( sv ...

Need help restarting a timer I've built in Angular with just a click?

I am in the process of developing a compact application that will help me keep track of my activities within a specific time frame. Once I input an activity into a field and click "OK," it should be added to a list. My current challenge lies in resetting ...

Error when attempting to add data into MongoDB using Node.JS: "The type 'string' cannot be assigned to type 'ObjectId | undefined'."

Attempting to add a document to the collection results in an error when specifying the _id field of the added document. How can I insert a document with an _id that is not an ObjectId? The error occurs with the following code. Omitting the _id resolves th ...

The fieldset css in PrimeNG differs from the website's original design

On my website, the appearance of the fieldset can be seen here: https://i.stack.imgur.com/TTS8s.jpg. I did not make any CSS changes that altered the fieldset. I am utilizing primeNG v7 and Angular 7. <p-fieldset legend="Toggleable" [toggleable]="true" ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

Tips for developing integration tests for medium-sized nodejs applications with heavy reliance on 3rd party APIs

I am the owner of a medium-sized nodejs application that can be found on GitHub under the link here. This application heavily relies on various 3rd party APIs to function. Essentially, the purpose of this app is to make calls to different Salesforce APIs, ...

Guide to implementing basic authentication within an HTTP request in Angular 4

I'm new to this and I only have experience with the http post method. I need to send the username and password as base authentication for every API request. onSubmit = function(userdata){ this.tokenkey = localStorage.getItem('logintoken&apos ...

What is the correct way to define an abstract method within a class to ensure that an IDE detects and notifies if the abstract method is not implemented

Is there a way to properly define an abstract method in an abstract class and have the IDE notify us if we forget to implement it? I attempted the following approach, but it did not work: export abstract class MyAbstractClass { /** * @abstract ...

NX build failed with the following error message: "[readCachedProjectGraph] An issue occurred - there is no ProjectGraph cached at

I encountered an error while attempting to run my angular 13 application and I'm unsure of the cause. Any assistance would be greatly appreciated. The error message received is: "[error] Error: [readCachedProjectGraph] ERROR: No cached ProjectGr ...

Encountering problems while attempting to npm install on Windows with Git Bash for Angular.io's quick start tutorial

I am attempting to perform an npm install on windows for the Angular.io quick start, available at: https://angular.io/docs/ts/latest/guide/setup.html However, I encountered a git bash error after cloning the repository: shasum check failed for... This i ...

Unable to locate module 'fs'

Hey there, I'm encountering an issue where the simplest Typescript Node.js setup isn't working for me. The error message I'm getting is TS2307: Cannot find module 'fs'. You can check out the question on Stack Overflow here. I&apos ...

Facing challenges with parsing JSON files in an Angular 2+ application

Utilizing the Angular CLI, I have configured this project with the standard folder layout. My goal is to practice reading a JSON file from src/app/assets/items.json and then using it to display these items in the HTML. items.json: { "results": [ ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

What connections exist between systemjs.config.js and .import() in Angular2/SystemJS?

My journey to learn Angular2 has led me to various Stack Exchange posts and internet articles discussing the function of systemjs.config.js. However, I've noticed that most explanations tend to use the term "app" excessively. For example, when index. ...

Prompt the user to take an action by opening a modal or dialogue box from a dropdown menu

I am looking to implement a functionality where a modal or dialogue will be opened when a user selects an option from a dropdown menu. As the dropdown menu will have multiple options, different dialogues/modals should appear based on the selected option. ...

Exploring the world of Vue and Pinia: managing and accessing data like

While delving into Vue and Pinia, I encountered a data management issue on the user side. On my main page, I showcase categories and auction items. However, upon navigating to a specific category in the catalog, the data for auction items remains in the st ...

Issue with loading CSS in Angular 8 upon refreshing the page after building in production

Here is the structure of my index.html: <!doctype html> <html lang="hu"> <head> <meta charset="utf-8"> <title>WebsiteName</title> <base href="/"> <meta name="viewport& ...

The efficiency of React Context API's setters is remarkably sluggish

I have a goal to implement a functionality where the background gradient of a page changes depending on whether the child's sublinks are expanded or collapsed. To achieve this, I am using the useContext hook. However, I've noticed that although e ...