• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript testing.HttpTestingController类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了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;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript testing.TestRequest类代码示例发布时间:2022-05-28
下一篇:
TypeScript xsrf.HttpXsrfInterceptor类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap