Invalid provider for the NgModule 'DynamicTestModule' when testing a service in Angular 2

Cristian picture Cristian · Feb 1, 2017 · Viewed 14.4k times · Source

I have the following service:

import { Injectable } from '@angular/core';

import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

@Injectable()
export class ItemsListService {

    getItems(): Promise<MenuItem[]> {
        return Promise.resolve(ITEMS);
    }

}

The test for this service is here:

import { TestBed, async, inject } from '@angular/core/testing';

import { ItemListService } from './item-list.service';
import { MenuItem } from './../classes/menu-item';
import { ITEMS } from './../static-data/items-list';

describe('ItemListService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [ ItemListService, MenuItem, ITEMS ]
    });
  });

  it('should ...', inject([ItemListService], (service: ItemListService) => {
    expect(service).toBeTruthy();
  }));
});

The MenuItem is defined here:

export class MenuItem {
    name: string;
    link: string;
}

ITEMS is defined here: import { MenuItem } from './../classes/menu-item';

export var ITEMS: MenuItem[] = [
    {name: 'Vehicles', link: '/vehicles'},
    {name: 'Gateways', link: '/gateways'},
    {name: 'Statuses', link: '/statuses'},
    {name: 'Logs', link: '/logs'}
]

When I run the test I am getting in the browsers console the followings errors:

FAILED ItemListService should ...

and

enter image description here

So why do I have these errors? And what is the solution for the test to work?

Answer

Craig picture Craig · Nov 18, 2017

This is such an annoying error, thought I'd include another subtle cause to look for in your spec. In my case I specified 'provider' instead of 'provide' as below

 TestBed.configureTestingModule({
      providers: [{provider: ApplicationActions, useClass: ActionMock}] // don't do that (missing 'provide')!

rather than offer useful information like "no 'provide' key specified" it simply reports

Failed: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [?[object Object]?, ...]