當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript testing.HttpTestingController類代碼示例

本文整理匯總了TypeScript中@angular/common/http/testing.HttpTestingController的典型用法代碼示例。如果您正苦於以下問題:TypeScript HttpTestingController類的具體用法?TypeScript HttpTestingController怎麽用?TypeScript HttpTestingController使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了HttpTestingController類的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: describe

describe('HttpService', () => {
  let httpCacheService: HttpCacheService;
  let http: HttpClient;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        ErrorHandlerInterceptor,
        CacheInterceptor,
        ApiPrefixInterceptor,
        HttpCacheService,
        {
          provide: HttpClient,
          useClass: HttpService
        }
      ]
    });
  });

  beforeEach(inject(
    [HttpClient, HttpTestingController, HttpCacheService],
    (
      _http: HttpClient,
      _httpMock: HttpTestingController,
      _httpCacheService: HttpCacheService
    ) => {
      http = _http;
      httpMock = _httpMock;
      httpCacheService = _httpCacheService;
    }
  ));

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

  it('should use error handler, API prefix and no cache by default', () => {
    // Arrange
    let interceptors: HttpInterceptor[];
    const realRequest = http.request;
    spyOn(HttpService.prototype, 'request').and.callFake(function(this: any) {
      interceptors = this.interceptors;
      return realRequest.apply(this, arguments);
    });

    // Act
    const request = http.get('/toto');

    // Assert
    request.subscribe(() => {
      expect(http.request).toHaveBeenCalled();
      expect(
        interceptors.some(i => i instanceof ApiPrefixInterceptor)
      ).toBeTruthy();
      expect(
        interceptors.some(i => i instanceof ErrorHandlerInterceptor)
      ).toBeTruthy();
      expect(interceptors.some(i => i instanceof CacheInterceptor)).toBeFalsy();
    });
    httpMock.expectOne({}).flush({});
  });

  it('should use cache', () => {
    // Arrange
    let interceptors: HttpInterceptor[];
    const realRequest = http.request;
    spyOn(HttpService.prototype, 'request').and.callFake(function(this: any) {
      interceptors = this.interceptors;
      return realRequest.apply(this, arguments);
    });

    // Act
    const request = http.cache().get('/toto');

    // Assert
    request.subscribe(() => {
      expect(
        interceptors.some(i => i instanceof ApiPrefixInterceptor)
      ).toBeTruthy();
      expect(
        interceptors.some(i => i instanceof ErrorHandlerInterceptor)
      ).toBeTruthy();
      expect(
        interceptors.some(i => i instanceof CacheInterceptor)
      ).toBeTruthy();
    });
    httpMock.expectOne({}).flush({});
  });

  it('should skip error handler', () => {
    // Arrange
    let interceptors: HttpInterceptor[];
    const realRequest = http.request;
    spyOn(HttpService.prototype, 'request').and.callFake(function(this: any) {
      interceptors = this.interceptors;
      return realRequest.apply(this, arguments);
    });
//.........這裏部分代碼省略.........
開發者ID:epot,項目名稱:Gifter,代碼行數:101,代碼來源:http.service.spec.ts

示例2: describe

describe('RoleService', () => {
  let service: RoleService;
  let httpTesting: HttpTestingController;

  configureTestBed({
    providers: [RoleService],
    imports: [HttpClientTestingModule]
  });

  beforeEach(() => {
    service = TestBed.get(RoleService);
    httpTesting = TestBed.get(HttpTestingController);
  });

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

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should call list', () => {
    service.list().subscribe();
    const req = httpTesting.expectOne('api/role');
    expect(req.request.method).toBe('GET');
  });

  it('should call delete', () => {
    service.delete('role1').subscribe();
    const req = httpTesting.expectOne('api/role/role1');
    expect(req.request.method).toBe('DELETE');
  });

  it('should call get', () => {
    service.get('role1').subscribe();
    const req = httpTesting.expectOne('api/role/role1');
    expect(req.request.method).toBe('GET');
  });

  it('should check if role name exists', () => {
    let exists: boolean;
    service.exists('role1').subscribe((res: boolean) => {
      exists = res;
    });
    const req = httpTesting.expectOne('api/role');
    expect(req.request.method).toBe('GET');
    req.flush([{ name: 'role0' }, { name: 'role1' }]);
    expect(exists).toBeTruthy();
  });

  it('should check if role name does not exist', () => {
    let exists: boolean;
    service.exists('role2').subscribe((res: boolean) => {
      exists = res;
    });
    const req = httpTesting.expectOne('api/role');
    expect(req.request.method).toBe('GET');
    req.flush([{ name: 'role0' }, { name: 'role1' }]);
    expect(exists).toBeFalsy();
  });
});
開發者ID:C2python,項目名稱:ceph,代碼行數:62,代碼來源:role.service.spec.ts

示例3: describe

describe('RbdTrashPurgeModalComponent', () => {
  let component: RbdTrashPurgeModalComponent;
  let fixture: ComponentFixture<RbdTrashPurgeModalComponent>;
  let httpTesting: HttpTestingController;

  configureTestBed({
    imports: [
      HttpClientTestingModule,
      ReactiveFormsModule,
      SharedModule,
      ToastModule.forRoot(),
      RouterTestingModule
    ],
    declarations: [RbdTrashPurgeModalComponent],
    providers: [BsModalRef]
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(RbdTrashPurgeModalComponent);
    httpTesting = TestBed.get(HttpTestingController);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  it(
    'should finish ngOnInit',
    fakeAsync(() => {
      component.poolPermission = new Permission(['read', 'create', 'update', 'delete']);
      fixture.detectChanges();
      const req = httpTesting.expectOne('api/pool?attrs=pool_name,application_metadata');
      req.flush([
        {
          application_metadata: ['foo'],
          pool_name: 'bar'
        },
        {
          application_metadata: ['rbd'],
          pool_name: 'baz'
        }
      ]);
      tick();
      expect(component.pools).toEqual(['baz']);
      expect(component.purgeForm).toBeTruthy();
    })
  );

  it('should call ngOnInit without pool permissions', () => {
    component.poolPermission = new Permission([]);
    component.ngOnInit();
    httpTesting.expectOne('api/summary');
    httpTesting.verify();
  });

  describe('should call purge', () => {
    let notificationService: NotificationService;
    let modalRef: BsModalRef;
    let req;

    beforeEach(() => {
      fixture.detectChanges();
      notificationService = TestBed.get(NotificationService);
      modalRef = TestBed.get(BsModalRef);

      component.purgeForm.patchValue({ poolName: 'foo' });

      spyOn(modalRef, 'hide').and.stub();
      spyOn(component.purgeForm, 'setErrors').and.stub();
      spyOn(notificationService, 'show').and.stub();

      component.purge();

      req = httpTesting.expectOne('api/block/image/trash/purge/?pool_name=foo');
    });

    it('with success', () => {
      req.flush(null);
      expect(component.purgeForm.setErrors).toHaveBeenCalledTimes(0);
      expect(component.modalRef.hide).toHaveBeenCalledTimes(1);
    });

    it('with failure', () => {
      req.flush(null, { status: 500, statusText: 'failure' });
      expect(component.purgeForm.setErrors).toHaveBeenCalledTimes(1);
      expect(component.modalRef.hide).toHaveBeenCalledTimes(0);
    });
  });
});
開發者ID:dillaman,項目名稱:ceph,代碼行數:91,代碼來源:rbd-trash-purge-modal.component.spec.ts

示例4: describe

describe('ApiInterceptorService', () => {
  let notificationService: NotificationService;
  let httpTesting: HttpTestingController;
  let httpClient: HttpClient;
  let router: Router;
  const url = 'api/xyz';

  const httpError = (error, errorOpts, done = (_resp) => {}) => {
    httpClient.get(url).subscribe(
      () => {},
      (resp) => {
        // Error must have been forwarded by the interceptor.
        expect(resp instanceof HttpErrorResponse).toBeTruthy();
        done(resp);
      }
    );
    httpTesting.expectOne(url).error(error, errorOpts);
  };

  const runRouterTest = (errorOpts, expectedCallParams) => {
    httpError(new ErrorEvent('abc'), errorOpts);
    httpTesting.verify();
    expect(router.navigate).toHaveBeenCalledWith(...expectedCallParams);
  };

  const runNotificationTest = (error, errorOpts, expectedCallParams) => {
    httpError(error, errorOpts);
    httpTesting.verify();
    expect(notificationService.show).toHaveBeenCalled();
    expect(notificationService.save).toHaveBeenCalledWith(expectedCallParams);
  };

  const createCdNotification = (type, title?, message?, options?, application?) => {
    return new CdNotification(new CdNotificationConfig(type, title, message, options, application));
  };

  configureTestBed({
    imports: [AppModule, HttpClientTestingModule],
    providers: [
      NotificationService,
      i18nProviders,
      {
        provide: ToastsManager,
        useValue: {
          error: () => true
        }
      }
    ]
  });

  beforeEach(() => {
    const baseTime = new Date('2022-02-22');
    spyOn(global, 'Date').and.returnValue(baseTime);

    httpClient = TestBed.get(HttpClient);
    httpTesting = TestBed.get(HttpTestingController);

    notificationService = TestBed.get(NotificationService);
    spyOn(notificationService, 'show').and.callThrough();
    spyOn(notificationService, 'save');

    router = TestBed.get(Router);
    spyOn(router, 'navigate');
  });

  it('should be created', () => {
    const service = TestBed.get(ApiInterceptorService);
    expect(service).toBeTruthy();
  });

  describe('test different error behaviours', () => {
    beforeEach(() => {
      spyOn(window, 'setTimeout').and.callFake((fn) => fn());
    });

    it('should redirect 401', () => {
      runRouterTest(
        {
          status: 401
        },
        [['/login']]
      );
    });

    it('should redirect 403', () => {
      runRouterTest(
        {
          status: 403
        },
        [['/403']]
      );
    });

    it('should show notification (error string)', () => {
      runNotificationTest(
        'foobar',
        {
          status: 500,
          statusText: 'Foo Bar'
        },
//.........這裏部分代碼省略.........
開發者ID:ceph,項目名稱:ceph,代碼行數:101,代碼來源:api-interceptor.service.spec.ts

示例5: beforeEach

 beforeEach(() => {
   testData = getTestContribs();
   httpMock.expectOne({}).flush(testData);
   contribService.contributors.subscribe(results => contribs = results);
 });
開發者ID:BobChao87,項目名稱:angular,代碼行數:5,代碼來源:contributor.service.spec.ts

示例6: it

 it(`should call the API once even if it is called multiple times`, fakeAsync(() => {
   expectSettingsApiCall(exampleUrl, { value: exampleValue }, exampleValue);
   testConfig(exampleUrl, exampleValue);
   httpTesting.expectNone(exampleUrl);
   expect(increment).toBe(2);
 }));
開發者ID:tone-zhang,項目名稱:ceph,代碼行數:6,代碼來源:settings.service.spec.ts

示例7: afterEach

 afterEach(() => {
   httpClient.verify();
 });
開發者ID:ehunter-usgs,項目名稱:earthquake-eventpages,代碼行數:3,代碼來源:text-product.component.spec.ts

示例8: afterEach

 afterEach(() => {
   mockBackend.verify();
 });
開發者ID:JonZeolla,項目名稱:incubator-metron,代碼行數:3,代碼來源:grok-validation.service.spec.ts

示例9: it

 it('should call delete', () => {
   service.delete('role1').subscribe();
   const req = httpTesting.expectOne('api/role/role1');
   expect(req.request.method).toBe('DELETE');
 });
開發者ID:C2python,項目名稱:ceph,代碼行數:5,代碼來源:role.service.spec.ts

示例10: httpError

 const runNotificationTest = (error, errorOpts, expectedCallParams) => {
   httpError(error, errorOpts);
   httpTesting.verify();
   expect(notificationService.show).toHaveBeenCalled();
   expect(notificationService.save).toHaveBeenCalledWith(expectedCallParams);
 };
開發者ID:ceph,項目名稱:ceph,代碼行數:6,代碼來源:api-interceptor.service.spec.ts


注:本文中的@angular/common/http/testing.HttpTestingController類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。