在Angular 2中测试服务时,NgModule'DynamicTestModule'的提供程序无效 [英] Invalid provider for the NgModule 'DynamicTestModule' when testing a service in Angular 2
问题描述
我有以下服务:
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'导入{MenuItem};
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?
推荐答案
这是一个令人讨厌的错误,以为我会在您的规范中寻找另一个细微的原因.在我的情况下,我指定了"provider"而不是如下的"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 '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
失败: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屋!