NgModule' DynamicTestModule'的提供商无效。在Angular 2中测试服务时

时间:2017-02-01 12:46:13

标签: javascript angular testing angular-services

我有以下服务:

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);
    }

}

这项服务的测试在这里:

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();
  }));
});

MenuItem在此处定义:

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

ITEMS在这里定义: 从&#39; ./../ classes / menu-item&#39;;

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

当我运行测试时,我在浏览器控制台中遇到以下错误:

FAILED ItemListService should ...

enter image description here

那为什么我会有这些错误?测试工作的解决方案是什么?

2 个答案:

答案 0 :(得分:40)

这是一个令人讨厌的错误,我想我会在你的规范中包含另一个微妙的原因。在我的情况下,我指定了“提供者”而不是“提供”,如下所示

 TestBed.configureTestingModule({
      providers: [{provider: ApplicationActions, useClass: ActionMock}]

而不是提供有用的信息,例如“不'提供'指定键',它只是报告

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

答案 1 :(得分:0)

我有同样的问题,在我的 Ionic Framework 项目中这样导入时:

import {Device} from '@ionic-native/device'

代替:

import {Device} from '@ionic-native/device/ngx'