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 missing async pipe has caused an error in Spartacus when attempting to lazily load CMS components

Having trouble implementing Lazy Loading of CMS Components, I encountered the following error: ERROR Error: The pipe 'async' could not be found! It works perfectly with CSR, but SSR is giving issues. Using Spartacus 3.2.2 and Angular 10.2.3 in ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Does the layout.tsx file in Next JS only affect the home page, or does it impact all other pages as well?

UPDATE After some troubleshooting, I've come to realize that the issue with my solution in Next JS 13 lies in the structure of the app. Instead of using _app.tsx or _document.tsx, the recommended approach is to utilize the default layout.tsx. Althou ...

Getting JSON or JSONP data through a XAMPP local server is a straightforward process

After setting up a local server with XAMPP, my goal is to retrieve JSON / JSONP data from that server. Additional query: Do I need to upload the JSON file directly onto the server? Or can I achieve this using somePHPcoding? If so, which? I have come ac ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

invalid audio element

I'm currently working on building an audio player with a visualizer feature. However, when I try to initiate the audio player by clicking on the input button, my debug console keeps showing this error message: Uncaught (in promise) DOMException: Fa ...

What is the method for incorporating PHP's header() function within PayPal JavaScript code?

I'm currently working on integrating Paypal with my website and I've run into some issues handling the various messages sent by Paypal, such as success, failed, and cancelled transactions. Below is a snippet of the Paypal JS code where it manage ...

Setting up Laravel with pjax

For the first time, I am experimenting with using pjax in combination with Laravel to enhance page loading speed. Since I am not well-acquainted with this technology yet, I have integrated this package into my project. Everything appears to be functioning ...

While using axios to make a GET request, I encountered errors when checking for .isSuccess in react

const searchInvoiceList = async ( plantLocation: string, invoiceType: string ) => { let dataList: InvoiceData[] = []; await axios .get(`${linkURL}inv/getControlList/${plantLocation}/${invoiceType}`) .then((response) => { dataLis ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

"JavaScript issue: receiving 'undefined' when trying to retrieve input

This code snippet is for a web app that tracks the number of losses in a game. The problem arises when trying to retrieve the value, which returns undefined. Every time I reference the username variable, it returns undefined. document.addEventListener(&a ...

Issue with string interpolation failing to correctly reflect the updated value from the service provider

I created a simple component to test string interpolation in HTML, <p>{{value}}</p> Here is the TypeScript file: export class HelloComponent implements OnInit { value: any; constructor(private service: ApiService) { this.value = ...

Solving the Challenge of URL Issue in Ajax Call to MVC Controller

I have searched extensively for a solution to my jQuery/MVC problem, but haven't found one that works. Here is the JavaScript code I am using: $.ajax({ type: "POST", url: '@Url.Action("Search","Controller")& ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

Unable to start an expo project in bare workflow using TypeScript

Can someone help me with setting up an expo bare workflow using TypeScript? I ran the command "expo init [project name]" in my terminal, but I can't seem to find the minimal (TypeScript) option. ? Choose a template: » - Use arrow-keys. Return to sub ...

Create a debounce click directive for buttons in a TypeScript file

I'm facing an issue with implementing debounce click on a dynamically added button using TypeScript. I need help with the correct syntax to make it work. private _initActionsFooter(): void { this.actionsFooterService.add([ { ...

Filtering an object based on a particular string

Is there a way to filter an array based on a string value? I want to display only the rows that contain this specific string or any part of it. For example, consider the following object: 0: {CurrentDriverElement: null, FullName: "1043 TU 147", ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

Development in Angular 2 with a team of developers utilizing TFVC for version control and managing node_modules

With over 20,000 files in the node_modules directory, it may not be practical to include them in source control. This results in developers having to run 'npm install' every time they perform a 'get latest' in order to download any mis ...