在测试具有依赖关系的组件时,如何在角度组件测试中不导入无用的导入?

时间:2017-08-17 16:06:39

标签: angular typescript jasmine karma-runner

我无法弄清楚这段代码有什么问题。它一直告诉我没有AlertService的提供者。我提供了AlertServiceSpy类,但它仍然说没有AlertService的提供程序。一旦我将CoreModule和RouterTestingModule添加到导入它就开始工作。

这必须是因为AlertService依赖于它们,但是在这个测试中这完全不重要。我只想测试AlertComponent并且不关心AlertService的依赖关系,因此我嘲笑它。为什么我需要将AlertService的依赖项导入此测试?请帮忙!

describe('AlertComponent', () => {

  let comp: AlertComponent;
  let fixture: ComponentFixture<AlertComponent>;
  let de: DebugElement;
  let el: HTMLElement;
  let alertService: any;

  class AlertServiceSpy {

    getMessage = jasmine.createSpy('getMessage').and.callFake(
        () => Observable
            .create((observer) => {
                return 'message';
            })
    );

  }


  beforeEach(async(() => {

    TestBed.configureTestingModule({
      imports: [
      ],
      declarations: [        
        AlertComponent
      ],
      providers: [
        { provide: AlertService, useClass: AlertServiceSpy }
      ]

    }).overrideComponent(AlertComponent, {

      set: {
        providers: [
          { provide: AlertService, useClass: AlertServiceSpy }
        ]
      }

    }).compileComponents();

    fixture = TestBed.createComponent(AlertComponent);
    }));
  });

  // TESTS
  it('true is true', () => expect(true).toBe(true));

});

警报组件:

import { Component, OnInit } from '@angular/core';
import { AlertService } from '../Alert/alert.service';

@Component({
    moduleId:       module.id,
    selector:       'app-alert-system',
    templateUrl:    'alert.component.html',
})

export class AlertComponent implements OnInit {

    public message: any;

    constructor( private alertService: AlertService) {}

    ngOnInit() {
        this.alertService.getMessage().subscribe(
            message => { 
                this.message = message; 
            });
    }
}

提醒服务:

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HttpAlertGenerator } from './http-alert-generator'

/*
    Service used for handling alerts.
*/
@Injectable()
export class AlertService {

    private _subject = new Subject<any>();
    private _keepAfterNavigationChange = false;
    private _httpAlertGenerator = new HttpAlertGenerator();

    constructor(private router: Router) {

        router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this._keepAfterNavigationChange) {
                    this._keepAfterNavigationChange = false;
                } else {
                    this._subject.next();
                }
            }
        });

    }

    // public
    public httpAlert(errCode: number, 
                     additionalInfo: string,
                     keepAfterNavigationChange = true, 
                     displayDurationInMillis?: number) {

        const message = additionalInfo + ' ' + this._httpAlertGenerator.codeToMessage(errCode);

        if (errCode >= 300) {
            this.error(message, keepAfterNavigationChange);
        } else {
            this.success(message, keepAfterNavigationChange);
        }
    }

    public success(message: string, keepAfterNavigationChange = true, timeLimit = 5000) {
        this._keepAfterNavigationChange = keepAfterNavigationChange;
        this._subject.next({type: 'success', text: message});
        this.prepareNext(timeLimit);
    }

    public error(message: string, keepAfterNavigationChange = true) {
        this._keepAfterNavigationChange = keepAfterNavigationChange;
        this._subject.next({type: 'error', text: message});
    }

    // FOR ALERT COMPONENT
    public getMessage(): Observable<any> {
            return this._subject.asObservable();
    }

    private prepareNext(timelimit = 5000) {
        const nextSubj = this._subject;
        setTimeout(function(){
            nextSubj.next();
        }, timelimit);
    }
}

1 个答案:

答案 0 :(得分:0)

我似乎找到了问题,它基本上与测试本身无关,而且有点奇怪。

问题是在某个地方,我将文件夹名称从大写更改为小写。 Git没有识别出这个变化,并保留了旧的文件夹名称。

在我的AlertComponent中,我从../Alert/alert.service导入了该服务,而我仍然在同一个文件夹中。我将其更改为./alert.service,这件事神奇地开始工作了。似乎我必须更加小心地命名我的文件夹。

我从以下文章中得到了提示:

Angular 2 - No Provider error (even though I've added a provider)