【问题标题】:Angular 2 unit test case is not working for services with external module configurationAngular 2 单元测试用例不适用于具有外部模块配置的服务
【发布时间】:2017-03-30 08:54:05
【问题描述】:

如果我使用 @Inject 方法创建一个带有服务的模块,则不适用于 Angular 2 Testbed 单元测试用例。它正在抛出 No Provider for AppService 错误。

  1. app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppService } from './app.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    {provide:'AppService',useClass:AppService}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. app.component.ts

import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor(@Inject('AppService') private appService) {}

  getName() {
    this.title = this.appService.getName();
  }

  setName(name) {
    this.appService.setName(name);
  }
}
  1. app.service.ts

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

@Injectable()
export class AppService {
  private name = 'dummy';

  public getName() {
    return this.name;
  }

  public setName(name) {
    console.log("ser", name);
    this.name = name;
  }
}
  1. app.component.spec.ts

import { Injectable} from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

import { AppService } from './app.service';


describe('AppComponent', () => {

  let fixture, comp, appService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [
        AppComponent
      ],
      providers: [AppService]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.debugElement.componentInstance;
    appService = fixture.debugElement.injector.get(AppService);
  });



  it('should create the app', async(() => {
    expect(comp).toBeTruthy();
  }));

});

【问题讨论】:

    标签: unit-testing angular provider


    【解决方案1】:

    尝试在 app.component.ts 中的@Component 中添加提供者:[AppService],如下所示

    @Component({
    providers: [AppService],
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    

    【讨论】:

    • 如果我们直接给提供者,那是有效的。但我想在组件中使用 @Inject 装饰器。如果我们直接使用“AppService”,我们必须将它导入到组件中。相反,如果我们使用 @Inject 方法,我们可以在模块级别导入它并使用 @Inject 的所有组件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    相关资源
    最近更新 更多