繁体   English   中英

角度测试 - 如何测试调用两个服务的可观察链?

[英]Angular testing - How to test an observable chain where two services are called?

我正在尝试测试一个可观察的链,其中调用了 2 个服务。 我正在尝试测试这两个服务是否只被调用一次。 由于这两个服务都返回 observable,我使用mergeMap来链接调用,如下所示:

app.component.ts

public aliceInChain(): void {
    this.serviceA
      .doSomething()
      .pipe(
        mergeMap(() => {
          return this.serviceB.doSomethingElse();
        })
      )
      .subscribe(r => {
        console.log(r);
      });
  }

在我的规范文件中,我有:

describe("AppComponent", () => {
  let fixture;
  let component;

  beforeEach(async(() => {
    const serviceASpy = jasmine.createSpyObj("serviceA", {
      doSomething: of()
    });

    const serviceBSpy = jasmine.createSpyObj("serviceB", {
      doSomethingElse: of()
    });

    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [AppComponent],
      providers: [
        { provide: ServiceA, useValue: serviceASpy },
        { provide: ServiceB, useValue: serviceBSpy }
      ]
    }).compileComponents();
  }));

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



  fit("should call serviceA and serviceB", done => {

    component.aliceInChain();
    expect(component.serviceA.doSomething).toHaveBeenCalledTimes(1);


  });
});

我可以确保调用了第一个服务,但如何测试第二个服务是否也被调用? 这可能是被测试的方法无效吗?

我不会测试服务是否被调用,而是测试subscribe发生的事情。

describe("AppComponent", () => {
  let fixture;
  let component;
  let serviceASpy;
  let serviceBSpy;

  beforeEach(async(() => {
    serviceASpy = jasmine.createSpyObj("serviceA", ['doSomething']);

    serviceBSpy = jasmine.createSpyObj("serviceB", ['doSomethingElse']);

    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [AppComponent],
      providers: [
        { provide: ServiceA, useValue: serviceASpy },
        { provide: ServiceB, useValue: serviceBSpy }
      ]
    }).compileComponents();
  }));

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

  fit("should call serviceA and serviceB", done => {
    serviceASpy.doSomething.and.returnValue(of('hello')); // assuming doSomething returns an Observable<string>;
    serviceBSpy.doSomethingElse.and.returnValue(of('hello world')); // assuming doSomething else returns an Observable<string>
    component.aliceInChain();
    // not sure if the next two lines will work
    expect(component.serviceA.doSomething).toHaveBeenCalledTimes(1);
    expect(component.serviceB.doSomethingElse).toHaveBeenCalledTimes(1);
    // assert what should happen in the subscribe
    expect(console.log).toHaveBeenCalledWith('hello world');
    done();
  });
});

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM