使用带有管道的HttpTestingController进行Angular 6单元测试(map())

时间:2018-11-07 01:42:11

标签: unit-testing jasmine angular6 karma-jasmine angular-httpclient

在我的Jasmine单元测试中,有这样的服务:

getData() {    
    OtherService.getProtocol().pipe(
          map((protocol) => {
            this.protocol = protocol;
            return this.http.get(path);
          }))
}

现在为了测试这一点,我使用以下方法模拟了otherService:

otherService = jasmine.createSpyObj('OtherService', ['getProtocol']);
otherService.getProtocol.and.returnValue(of(fakeValue));

这部分经过验证可以正常工作。

但是在单元测试期间,即使直接调用map(),我也无法捕获在.verify()内部发出的http请求

describe('DeeplinkService', () => {
  let injector: TestBed;
  let otherService;
  let myService: MyService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    otherService = jasmine.createSpyObj('OtherService', ['getProtocol']);
    otherService.getProtocol.and.returnValue(of(fakeValue));
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [
        MyService,
        { provide: OtherService, useValue: otherService },
      ]
    });
    injector = getTestBed();
    myService = injector.get(MyService);
    httpMock = injector.get(HttpTestingController);
  });

  afterEach(() => {
    httpMock.verify();
  });

  it('fake test', () => {
      myService.getData().subscribe();
      httpMock.verify();  // <== Pass w/o fail
    }
  );

});

任何主意出了什么问题吗? 预先谢谢你!

0 个答案:

没有答案