简体   繁体   English

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

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

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

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

ITEMS is defined here: import { MenuItem } from './../classes/menu-item'; ITEMS 在这里定义: 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

在此处输入图像描述

So why do I have these errors?那么为什么我会出现这些错误呢? And what is the solution for the test to work?测试工作的解决方案是什么?

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]?, ...]失败:NgModule 'DynamicTestModule' 的提供者无效 - 仅允许提供者和类型的实例,得到:[?[object Object]?, ...]

BTW also mind to use the class in providers, not some variable.顺便说一句,还介意在提供商中使用 class,而不是一些变量。 This happened to me due to an accidental problematic replacement/casing:由于意外的问题更换/外壳,这发生在我身上:

Correct正确的

 TestBed.configureTestingModule({
    // ...
    providers: [ SomeService ]
}

instead of...代替...

Incorrect不正确

 TestBed.configureTestingModule({
    // ...
    providers: [ someService ]
}

Note the camelCase variable ( someService ) is likely there if you use it in your test, that's why it does not throw a syntax error.请注意,如果您在测试中使用驼峰命名法变量 ( someService ),则它可能存在,这就是它不会引发语法错误的原因。

I have same problem, when importing in my Ionic Framework project like this:我有同样的问题,在我的Ionic Framework项目中导入时是这样的:

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

instead of:而不是:

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

In my case, I had a stray comma in one of my provider lines, causing the DynamicTestModule to think I had passed an undefined definition.就我而言,我的提供程序行中有一个杂散逗号,导致DynamicTestModule认为我传递了一个undefined定义。

        {
          provide: ApiService,
          useValue: {
            getUsers: jasmine
              .createSpy('getUsers')
              .and.returnValue(of({ status: 200, body: [] })),
          },
        },
        , // whoops!
        MessageService,
        { provide: Location, useValue: { back: jasmine.createSpy('back') } },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 添加提供程序@NgModule时,Angular2“没有服务提供程序!”错误 - Angular2 “No provider for Service!” error when provider is added @NgModule NullInjectorError: StaticInjectorError(DynamicTestModule) 在 Angular 2 中测试时 - NullInjectorError: StaticInjectorError(DynamicTestModule) When Testing in Angular 2 Angular2-无效的NgModule提供程序,仅允许提供程序和类型的实例 - Angular2 - Invalid provider for the NgModule only instances of Provider and Type are allowed Angular2-将服务注入服务时出现无效的提供程序错误 - Angular2 - Invalid provider error when injecting service into service 使用Jasmine在AngularJS中测试服务时未知的提供程序 - Unknown provider when testing service in AngularJS with Jasmine 在 Jasmine 中对 Angular 进行单元测试时,模拟注入到提供者中的自定义提供者 - Mocking custom provider injected into provider when unit testing Angular in Jasmine 为什么我无法在@NgModule中导入Angular 2服务? - Why I cannot import Angular 2 service in @NgModule? 测试Angular组件时的Jasmine spyOn服务 - Jasmine spyOn service when testing Angular component 未知提供者:使用Jasmine测试角度控制器时的$ scopeProvider - Unknown Provider: $scopeProvider When Testing Angular Controller With Jasmine Angular NullInjectorError 没有服务提供商? - Angular NullInjectorError No Provider for Service?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM