在 Angular 2 中测试服务时,NgModule 'DynamicTestModule' 的提供程序无效 [英] Invalid provider for the NgModule 'DynamicTestModule' when testing a service in Angular 2

查看:24
本文介绍了在 Angular 2 中测试服务时,NgModule 'DynamicTestModule' 的提供程序无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下服务:

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 在这里定义:

The MenuItem is defined here:

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

ITEMS 在这里定义:从'./../classes/menu-item'导入{菜单项};

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 ...

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

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

推荐答案

这是一个令人讨厌的错误,我想我会在您的规范中包含另一个微妙的原因.在我的例子中,我指定了 providers 而不是 provide 的正确值,如下所示

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

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

而不是提供诸如未指定‘提供’密钥"之类的有用信息.它只是报告

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

失败:NgModule 'DynamicTestModule' 的提供者无效 - 仅限允许 Provider 和 Type 的实例,得到:[?[object Object]?,...]

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

这篇关于在 Angular 2 中测试服务时,NgModule 'DynamicTestModule' 的提供程序无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆