Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material.

During testing of my component (refer to the simplified code below), I encountered the following error:

Error: Error in ./MdTabHeader class MdTabHeader - inline template:0:0 caused by: No provider for ViewportRuler!
Error: No provider for ViewportRuler!

I attempted to resolve this issue by including ViewportRuler as a provider. However, when I did so (as shown in the commented out lines below), Karma returned:

Uncaught SyntaxError: Unexpected token import
at http://localhost:9876/context.html:10

After some research, it seems that the .ts file is being served to the browser instead of the compiled .js file. It's possible that I am referencing it incorrectly.

My main question is: how can I successfully compile my tests?

This is the code I have:

my.component.ts:

@Component({
    selector: 'test',
    template: require('./test.component.html')
})
export class TestComponent {

    items: any[];

    constructor() {
        this.items = [{ title: 'test 1', description: 'description 1' }, { title: 'test 2', description: 'description 2' }];
    }
}

my.component.html:

<md-tab-group>
    <md-tab *ngFor="let link of items">
        <template md-tab-label>
            <h4>{{link.title}}</h4>
        </template>
        {{link.description}}
    </md-tab>
</md-tab-group>    

my.component.spec.ts:

import { TestBed } from '@angular/core/testing';
import { Component} from '@angular/core';
import { MaterialModule } from '@angular/material';
import { ViewportRuler} from '@angular/material/core/overlay/position/viewport-ruler'
import { TestComponent } from './test.component';

describe("TestComponent",
    () => {
        let fixture, component;

        beforeEach(() => {

            TestBed.configureTestingModule({
                imports: [MaterialModule],
                declarations: [TestComponent],
                providers: [
                    //{ provide: ViewportRuler }    
                ]
            });

            fixture = TestBed.createComponent(TestComponent);
            component = fixture.componentInstance;
        });

        it('true = true', () => {
            expect(true).toBe(true);
        });        
    });

I've tried to provide as much detail as I can, but I'm quite new to the Angular environment. Please let me know if there's anything else you need from me.

Thank you!

Answer №1

Latest Update: version 2.0.0-beta.3

MaterialModule is now deprecated and developers are advised to use individual component modules or create custom modules based on their needs.

MaterialModule

  • The usage of MaterialModule (and MaterialRootModule) has been deemed deprecated.

Current tree-shaking techniques make it difficult for tools to eliminate unused code when using an aggregate NgModule like MaterialModule.

In order to optimize code size, MaterialModule is being deprecated and will be removed in future releases.

To replace MaterialModule, users can create a tailored "Material" module within their application (e.g., GmailMaterialModule) that only imports the components actually utilized in the app.

https://github.com/angular/material2/releases/tag/2.0.0-beta.3


Version 2.0.0-beta.2

The team at Material have eliminated the need for .forRoot(), making it obsolete.

The usage of Module.forRoot has been deprecated and will be phased out in upcoming releases. Instead, directly import MaterialModule:

@NgModule({
   imports: [
       ...
       MaterialModule,
       ...
   ]
...
});

https://github.com/angular/material2/releases/tag/2.0.0-beta.2


MaterialModule.forRoot() configures the providers required in a testing module. This should resolve issues like yours and similar ones such as No provider for MdIconRegistry!.

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

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

"Implementing a date picker in your Ionic 5 app: A step-by-step

How can I integrate a date picker similar to the Angular Material Date picker into my Ionic 5 application? I prefer not to use the native ion-datetime component due to limitations such as incomplete calendar display and lack of support for alternative ca ...

Transforming Poloniex API Callback JSON into a compatible format for Highcharts.Stockchart

I am currently working on a project that involves retrieving JSON data from Poloniex's public API method (specifically the returnChartData method) to generate a graph using Highchart Stockchart. The graph would display the historical performance of va ...

Loading custom Angular modules results in an error

Seems like a simple thing, but I'm struggling to figure it out on my own. I have an Angular application with the following key files: app/app.module.ts app/dashboard/dashboard.component.html app/dashboard/stats-tile/stats-tile.component.html I used ...

The call function in Tween.js fails to execute after adding an EventListener

I encountered an issue while using tween.0.6.2. The following code snippet (borrowed from the tween.js Getting Started page and slightly simplified) works perfectly: createjs.Tween.get(circle) .to({x: 400}, 1000, createjs.Ease.getPowInOut ...

Creating Mongoose models in TypeScript with multiple connections

Attempting to build a model with multiple connections as per the documentation, I encountered the following error: TS2345: Argument of type 'Schema<Document<any>, Model<Document<any>>>' is not assignable to parameter of ty ...

How do React Native proxies differ from vanilla React proxies in their functionality?

Trying to retrieve data from an API running locally on port 5000 of my device, I recalled setting the proxy in package.json when working on React web applications: "proxy": "https://localhost:5000" Attempting to fetch information f ...

JavaScript queries in Selenium WebDriver

Lately, I have been using the selenium webdriver (nodejs module) along with mocha for writing automation tests, and encountered a few challenges along the way. Issue with Scrolling driver.findElement() seems to return false as it is unable to find the e ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Adding a component to a page in Angular 4: A step-by-step guide

Currently engaged in a project that involves creating a mobile application design within a web application. I'm wondering how to display my Component object on a page using ViewChild? I have a list of PageComponents, below is the PageComponent class ...

Angular 14: Exploring the left datepicker panel navigation in PrimeNG

In my situation, I am trying to adjust the position of the date-picker in relation to a panel displayed within a <p-calendar> element. Due to a splitter on the right side, I need to shift the date-picker towards the left. Here is the HTML code: < ...

Tips on incorporating an item into an array solely when a specific condition is met

Consider the following arrow function that creates an array: const myFunction = () => ["a", "b", "c"]; I am looking to modify this function to add another element if a specific argument is true. For example, I want it to look like this: const myFunc ...

Gather information from users using Node.js and integrate it with Stripe

As I am new to Node.js, my goal is to utilize nodejs & Stripe to gather user data such as name, phone number, email, city, etc. This way, I can easily identify the user from the Stripe dashboard along with all their corresponding information. on the server ...

Guide to fixing Vue app crashes caused by Web Sockets error

I'm encountering an issue with my Vue application as I am unable to load a specific page due to the app crashing. The console displays the following error, even though there is no implementation of Web Sockets in the app. Despite adding this snippet ...

How to sort WordPress RSS feed in alphabetical order using JavaScript

Currently using WP, but feeling limited due to restricted access to PHP and plugins. Searching for a JAVASCRIPT code solution to fetch RSS feed from a URL and organize the feed titles in ALPHABETICAL order. The JS code can be inserted into the footer and ...

Can you use ng-show within ng-if in Angular?

How can I make this input only show a property is true per the ng-if? The current code looks like this: <input type="button" class="naviaBtn naviaBlue" ng-if="ppt.Globals.hasDebitCard" ng-click="alertShow = (alertShow == 2 ? -1 : 2)" value="outstandin ...

Issues with implementation of map and swiper carousel functionality in JavaScript

I am trying to populate a Swiper slider carousel with images from an array of objects. However, when I use map in the fetch to generate the HTML img tag with the image data, it is not behaving as expected. All the images are displaying in the first div a ...

Optimal method for parsing URLs using ES6

There have been many remarkable inquiries regarding this topic, such as: how to parse a url. However, as time has gone by, the answers I come across are outdated. I am looking for a more modern and flexible method to parse URLs, without relying on regular ...

I'm struggling to concentrate and unable to type in the email field

Today while working on a website, I encountered something strange. In the footer section of the site, there is a quick contact form. However, I noticed that in Firefox, I am unable to focus on the email field. Surprisingly, this issue does not occur in Chr ...

Invoke the HTTP API from the device application

I need to make an API call to a server that does not have the HTTPS protocol. I came across this post on Stack Overflow: https://stackoverflow.com/questions/57433362/api-calls-made-in-ionic-4-app-not-working-on-android-device The post mentions that HTTP ...