与提供者一起测试组件

问题描述 投票:0回答:1

我有一个服务SoundPanelService,用于服务隔离场景(如https://angular.io/guide/hierarchical-dependency-injection#scenario-service-isolation

@Injectable()
export class SoundPanelService {
  recorded = new Subject<Sound>();

  constructor() {
  }
}

我有 SoundPanelComponent

Component({
  selector: 'app-sound-panel',
  templateUrl: './sound-panel.component.html',
  styleUrls: ['./sound-panel.component.css'],
  providers: [SoundPanelService] // Service isolation 
})
export class SoundPanelComponent implements OnInit {
  recorded = new Subject<Sound>();

  constructor(private soundPanelService: SoundPanelService) {
    this.soundPanelService.recorded.subscribe((data) => {
      this.recorded.next(data);
    });
  }

  ngOnInit() {
  }

}

声音面板.component.html

<app-sound-player></app-sound-player>
<app-sound-recorder></app-sound-recorder>

SoundPlayer 和 SoundRecorder 通过服务 SoundPanelService 与 soundpanel 进行通信。

我想测试 SoundPanelComponent

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { SoundPanelComponent } from './sound-panel.component';
import { SoundRecorderComponent } from '../sound-recorder/sound-recorder.component';
import { SoundPlayerComponent } from '../sound-player/sound-player.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { SoundPanelService } from 'src/app/_services/sound-panel.service';
import { Sound } from 'src/app/_models/Sound';

describe('SoundPanelComponent', () => {
  let component: SoundPanelComponent;
  let fixture: ComponentFixture<SoundPanelComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SoundPanelComponent,
        SoundPlayerComponent,
        SoundRecorderComponent,
        SafeHtmlPipe
      ],
      imports: [HttpClientTestingModule],
      providers: [
      {
        provide: SoundPanelService, useClass: SoundPanelService
      }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SoundPanelComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should emit sound on new record from sound panel service',  async () => {
    const s: Sound = {base64: 'data:base64', mimeType: 'audio/wmw'};
    spyOn(component.recorded, 'next').and.callThrough();
    sps = TestBed.get(SoundPanelService);
    sps.recorded.next(s);
    fixture.detectChanges();
    fixture.whenStable().then(res => {
expect(component.recorded.next).toHaveBeenCalledTimes(1);
    });
  });
   
});

但我收到错误

SoundPanelComponent > 应该从声音面板服务发出新记录的声音 预计接下来的间谍会被召唤一次。被调用了 0 次。

如果我将 SoundPanelServiceprovidedIn: 'root' 我设法通过测试,但这不是我想要的,因为我希望 SoundPanelService 与每个 SoundPanelComponent 及其子组件隔离(我打算在同一页面上有许多 SoundPanelComponent)。

如何测试这个?

angular jasmine karma-runner angular8
1个回答
22
投票

已解决

使用了这个覆盖组件提供者

必须将代码更改为:

  1. 引入了.overrideComponent
 beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        SoundPanelComponent,
        SoundPlayerComponent,
        SoundRecorderComponent,
        SafeHtmlPipe
      ],
      imports: [HttpClientTestingModule]
    })
    .overrideComponent(SoundPanelComponent, {
      set: {
        providers: [
          { provide: SoundPanelService, useClass: SoundPanelService}
        ]
      }
    })
    .compileComponents();
  }));
  1. 从调试元素获取SoundPanelService:
it('should emit sound on new record from sound panel service',  async () => {
    const s: Sound = {base64: 'data:base64', mimeType: 'audio/wmw'};
    spyOn(component.recorded, 'next').and.callThrough();
    sps = fixture.debugElement.injector.get(SoundPanelService) as SoundPanelService;
    sps.recorded.next(s);
    fixture.detectChanges();
    fixture.whenStable().then(res => {
      expect(component.recorded.next).toHaveBeenCalledTimes(1);
    });
  });

测试通过!

© www.soinside.com 2019 - 2024. All rights reserved.