rxjs 运算符中的测试代码

Testing codes inside rxjs operator

我是 angular 茉莉花测试的新手,我想开始在我的应用程序中使用它,但我在测试覆盖率中包含 rxjs 运算符时遇到问题。

saveChanges(){
  this.isSaveSuccessful = false;
  this.saveService.httpGetCall()
   .pipe(tap( ret =>{
        line 1;
        line 2;
      }),
      map( ret => {
        line 3;
        line 4;
    }),
     finalize(()=>{
      if(someBoolean) this.isSaveSuccessful = true;
     })).subscribe()
}

第 1、2、3、4 行未包含在测试中。

it('should save',()=>{
  component.saveChanges();
  expect(component.isSaveSuccessful).toBeTrue();
})

您需要模拟从 this.saveService.httpGetCall() 返回的内容, 这是有关如何执行此操作的完整详细说明。 https://angular.io/guide/http

然后,一旦它被嘲笑,你就可以做这样的事情。

it('should save',()=>{
  component.saveChanges();
  mockedHttp.subscribe(result => {
   expect(result).toBe("your desired result");
  })
  expect(component.isSaveSuccessful).toBeTrue();
})

在 Jasmine 中模拟 saveService 并通过依赖注入 (DI) 为您的 component/service 提供它:

describe('MyComponent', () => {
  let saveService: SaveService:

  const yourCustomHttpGetCallResult = ...;

  beforeEach(() => {
    const saveServiceMock = jasmine.createSpyObj('SaveService', {
      httpGetCall: of(yourCustomHttpGetCallResult),
    });

    TestBed.configureTestingModule({
      declarations: [
        MyComponent,
      ],
      providers: [
        { provide: SaveService, useValue: saveServiceMock },
      ],
    });

    // create a component fixture
    ...

    saveService = TestBed.inject(SaveService);
  });

  it('should cover the lines 1, 2, 3, 4', () => {
    component.saveChanges();
  });

  it('should call saveChanges with another result', () => {
    const newCustomValue = ...;
    saveService.httpGetCall.and.returnValue(of(newCustomValue));

    component.saveChanges();
  });
});