当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript testing.async函数代码示例

本文整理汇总了TypeScript中@angular/core/testing.async函数的典型用法代码示例。如果您正苦于以下问题:TypeScript async函数的具体用法?TypeScript async怎么用?TypeScript async使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了async函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: describe

describe('SearchImComponent', () => {
  let fixture: ComponentFixture<SearchIntermodalComponent>;
  let component: SearchIntermodalComponent;
  let debugElement: DebugElement;

  let titleDomElement: DebugElement;
  let titleHtmlElement: HTMLElement;
  let inland: AbstractControl;

  const expectedCountries: Array<CountryModel> = [new CountryModel(1, 'GERMANY', 'DE'), new CountryModel(2, 'DANMARK', 'DK')];
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule, BrowserAnimationsModule, AppMaterialModule, ReactiveFormsModule],
      declarations: [SearchIntermodalComponent],
      providers: [EnumService, CountryService, GeoScopeService, IntermodalSearchService,
        {provide: ComponentFixtureAutoDetect, useValue: true}],
      // add NO_ERRORS_SCHEMA to ignore <app-result-intermodal> tag
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]

      // If you run tests in a non-CLI environment, compilationmight not have occured
    }).compileComponents();

  }));


  beforeEach(() => {
    // create component and test fixture
    // createComponent() does not bind data: use  fixture.detectChanges() to trigger this
    fixture = TestBed.createComponent(SearchIntermodalComponent);
    // get test component from the fixture
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    expect(component).toBeDefined();
    titleDomElement = fixture.debugElement.query(By.css('#im-search-form-title'));
    titleHtmlElement = titleDomElement.nativeElement;
    fillForm();
    inland = component.form.controls['inlandLocation'];

  });

  it('Component Should be Created', () => {
    expect(component).toBeTruthy();
  });

  it('should display original title', () => {
    // Hooray! No `fixture.detectChanges()` needed
    expect(titleHtmlElement.textContent).toContain(component.title);
  });

  it('should still see original title after comp.title change', () => {
    const oldTitle = component.title;
    component.title = 'Test Title';
    // Displayed title is old because Angular didn't hear the change :(
    expect(titleHtmlElement.textContent).toContain(oldTitle);
  });

  it('should display updated title after detectChanges', () => {
    component.title = 'Test Title';
    fixture.detectChanges(); // detect changes explicitly
    expect(titleHtmlElement.textContent).toContain(component.title);
  });

  it('DIV Element for Title should be established', () => {
    expect(titleDomElement).toBeTruthy();
    expect(titleHtmlElement).toBeTruthy();
    expect(titleHtmlElement.textContent).toContain('Search Key Figures');
  });

  it('Inland Location Is Missing: Form Should be Invalid', () => {

    let errors = {};
    inland = component.form.controls['inlandLocation'];
    errors = inland.errors || {};
    expect(errors['required']).toBeTruthy();

    expect(component.form.valid).toBeFalsy();
  });

  it('Inland Location Is Set: Form Should be Valid', () => {


    inland.setValue('DEDUS');
    fixture.detectChanges();
    expect(component.form.valid).toBeTruthy();
    expect(component.isInvalid()).toBeFalsy();
  });


  it('#MOST complex Test: Fills countryCode autocomplete which triggers reactive form observable which triggers service call', async(() => {
    const countryService: CountryService = debugElement.injector.get(CountryService);
    const spyService = spyOn(countryService, 'filterCountryCode').and.returnValue(of(expectedCountries));


    const geoScopeTypeControl = component.form.controls['inlandGeoScopeType'];
    geoScopeTypeControl.setValue('T');
    fixture.detectChanges();
    const countryControl: AbstractControl = component.form.controls['countryCode'];
    expect(countryControl).toBeDefined();
    expect(countryControl).toBeTruthy();
    expect(countryControl.value).toEqual('');
//.........这里部分代码省略.........
开发者ID:Eckhardo,项目名称:Aige_Angular,代码行数:101,代码来源:search-intermodal.component.spec.ts

示例2: testAsync

// Shortcut function for less boilerplate on each `it`
function testAsync(fn: (value: ComponentFixture<TestComponent>) => void, html: string = null) {
  return async(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.overrideTemplate(TestComponent, html).createAsync(TestComponent).then(fn);
  }));
}
开发者ID:Kabangi,项目名称:ng-lightning,代码行数:6,代码来源:svg.spec.ts

示例3: describe

describe("DynamicMaterialDatePickerComponent test suite", () => {

    let testModel = new DynamicDatePickerModel({id: "datepicker"}),
        formModel = [testModel],
        formGroup: FormGroup,
        fixture: ComponentFixture<DynamicMaterialDatePickerComponent>,
        component: DynamicMaterialDatePickerComponent,
        debugElement: DebugElement,
        testElement: DebugElement;

    beforeEach(async(() => {

        TestBed.configureTestingModule({

            imports: [
                ReactiveFormsModule,
                NoopAnimationsModule,
                MatDatepickerModule,
                MatInputModule,
                MatNativeDateModule,
                TextMaskModule,
                DynamicFormsCoreModule
            ],
            declarations: [DynamicMaterialDatePickerComponent]

        }).compileComponents().then(() => {

            fixture = TestBed.createComponent(DynamicMaterialDatePickerComponent);

            component = fixture.componentInstance;
            debugElement = fixture.debugElement;
        });
    }));

    beforeEach(inject([DynamicFormService], (service: DynamicFormService) => {

        formGroup = service.createFormGroup(formModel);

        component.group = formGroup;
        component.model = testModel;

        fixture.detectChanges();

        testElement = debugElement.query(By.css(`mat-datepicker`));
    }));

    it("should initialize correctly", () => {

        expect(component.control instanceof FormControl).toBe(true);
        expect(component.group instanceof FormGroup).toBe(true);
        expect(component.model instanceof DynamicDatePickerModel).toBe(true);
        expect(component.matDatePicker instanceof MatDatepicker).toBe(true);
        expect(component.matInput instanceof MatInput).toBe(true);

        expect(component.blur).toBeDefined();
        expect(component.change).toBeDefined();
        expect(component.customEvent).toBeDefined();
        expect(component.focus).toBeDefined();

        expect(component.onBlur).toBeDefined();
        expect(component.onChange).toBeDefined();
        expect(component.onFocus).toBeDefined();

        expect(component.hasFocus).toBe(false);
        expect(component.isValid).toBe(true);
        expect(component.isInvalid).toBe(false);
        expect(component.showErrorMessages).toBe(false);
    });

    it("should have an mat-datepicker element", () => {

        expect(testElement instanceof DebugElement).toBe(true);
    });

    it("should emit blur event", () => {

        spyOn(component.blur, "emit");

        component.onBlur(null);

        expect(component.blur.emit).toHaveBeenCalled();
    });

    it("should emit change event", () => {

        spyOn(component.change, "emit");

        component.onChange(null);

        expect(component.change.emit).toHaveBeenCalled();
    });

    it("should emit focus event", () => {

        spyOn(component.focus, "emit");

        component.onFocus(null);

        expect(component.focus.emit).toHaveBeenCalled();
    });
//.........这里部分代码省略.........
开发者ID:udos86,项目名称:ng2-dynamic-forms,代码行数:101,代码来源:dynamic-material-datepicker.component.spec.ts

示例4: describe

describe('Pages: Page2', () => {

  // demonstration on how to manually compile the test bed (as opposed to calling TestUtils)
  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [Page2],
      providers: [
        App, DomController, Form, Keyboard, MenuController, NavController,
        {provide: Config, useClass: ConfigMock},
        {provide: Platform, useClass: PlatformMock},
        {provide: AlertController, useValue: alertControllerMock},
      ],
      imports: [
        FormsModule,
        IonicModule,
        ReactiveFormsModule,
      ],
    })
    .compileComponents().then(() => {
      fixture = TestBed.createComponent(Page2);
      instance = fixture;
      fixture.detectChanges();
      fixture.componentInstance.onGainChange();

      alertSpy = fixture.componentInstance.alertController;
      alertControllerSpy = fixture.componentInstance.alertController.create();

    });
  }));

  afterEach(() => {
    fixture.destroy();
  });

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

  it('should fire the simple alert', fakeAsync(() => {

    alertSpy.create.calls.reset();
    alertControllerSpy.present.calls.reset();

    expect(alertSpy.create).not.toHaveBeenCalledTimes(1);
    expect(alertControllerSpy.present).not.toHaveBeenCalledTimes(1);

    expect(alertSpy.create).not.toHaveBeenCalled();
    expect(alertControllerSpy.present).not.toHaveBeenCalled();

    fixture.componentInstance.showSimpleAlert();
    tick();

    expect(alertSpy.create).toHaveBeenCalledTimes(1);
    expect(alertControllerSpy.present).toHaveBeenCalledTimes(1);

    expect(alertSpy.create).toHaveBeenCalled();
    expect(alertControllerSpy.present).toHaveBeenCalled();

  }));

  it('should fire the more advanced alert', fakeAsync(() => {

    alertSpy.create.calls.reset();
    alertControllerSpy.present.calls.reset();

    fixture.componentInstance.okEd = false;

    expect(fixture.componentInstance.okEd).toBeFalsy();

    fixture.componentInstance.showMoreAdvancedAlert();
    tick();

    fixture.componentInstance.OK();

    expect(fixture.componentInstance.okEd).toBeTruthy();

  }));

});
开发者ID:gpanos,项目名称:clicker,代码行数:81,代码来源:page2.spec.ts

示例5: describe

describe('SignupComponent', () => {

  @Component({
    template: `<mpt-signup></mpt-signup>`,
    directives: [SignupComponent],
  })
  class TestComponent {
  }

  let cmpDebugElement:DebugElement;

  let loginService:LoginService;
  let backend:MockBackend;
  let router:Router;
  let location:Location;

  beforeEachProviders(() => [APP_TEST_PROVIDERS]);
  beforeEach(prepareAppInjector());
  beforeEach(inject([LoginService, MockBackend, Router, Location], (..._) => {
    [loginService, backend, router, location] = _;
  }));
  beforeEach(async(inject([TestComponentBuilder], (tcb:TestComponentBuilder) => {
    tcb
      .createAsync(TestComponent)
      .then((fixture:ComponentFixture<any>) => {
        cmpDebugElement = fixture.debugElement.query(By.directive(SignupComponent));
        fixture.detectChanges();
      });
  })));

  it('can be shown', () => {
    expect(cmpDebugElement).toBeTruthy();
  });

  it('can validate inputs', () => {
    const page:SignupComponent = cmpDebugElement.componentInstance;
    page.name.updateValue('a', {});
    page.email.updateValue('b', {});
    page.password.updateValue('c', {});
    page.passwordConfirmation.updateValue('d', {});
    expect(page.myForm.valid).toBeFalsy();
    page.name.updateValue('akira', {});
    page.email.updateValue('test@test.com', {});
    page.password.updateValue('secret123', {});
    page.passwordConfirmation.updateValue('secret123', {});
    expect(page.myForm.valid).toBeTruthy();
  });

  it('can signup', (done) => {
    const page:SignupComponent = cmpDebugElement.componentInstance;
    spyOn(loginService, 'login').and.callThrough();
    backend.connections.subscribe(conn => {
      conn.mockRespond(new Response(new BaseResponseOptions()));
    });
    page.onSubmit({
      email: 'test@test.com',
      password: 'secret',
      name: 'akira',
    });
    expect(loginService.login).toHaveBeenCalledWith('test@test.com', 'secret');

    router.subscribe(() => {
      expect(location.path()).toEqual('/home');
      done();
    });
  });

});
开发者ID:cipengxu,项目名称:angular2-app,代码行数:68,代码来源:signup.component.spec.ts

示例6: describe

    describe('when template is ready', () => {
        let tabWidgetComponent: TabsWidgetComponent;
        let fixture: ComponentFixture<TabsWidgetComponent>;
        let element: HTMLElement;
        let fakeTabVisible: TabModel;
        let fakeTabInvisible: TabModel;

        beforeEach(async(() => {
            fixture = TestBed.createComponent(TabsWidgetComponent);
            tabWidgetComponent = fixture.componentInstance;
            element = fixture.nativeElement;

            fakeTabVisible = new TabModel(new FormModel(fakeFormJson), {
                id: 'tab-id-visible',
                title: 'tab-title-visible'
            });
            fakeTabVisible.isVisible = true;
            fakeTabInvisible = new TabModel(new FormModel(fakeFormJson), {
                id: 'tab-id-invisible',
                title: 'tab-title-invisible'
            });
            fakeTabInvisible.isVisible = false;
            tabWidgetComponent.tabs.push(fakeTabVisible);
            tabWidgetComponent.tabs.push(fakeTabInvisible);
        }));

        it('should show only visible tabs', fakeAsync(() => {
            fixture.detectChanges();

            tick(500);

            expect(element.innerText).toContain('tab-title-visible');
        }));

        it('should show tab when it became visible', fakeAsync(() => {
            fakeTabInvisible.isVisible = false;

            fixture.detectChanges();

            tick(500);

            tabWidgetComponent.formTabChanged.subscribe((res) => {
                tabWidgetComponent.tabs[1].isVisible = true;

                tick(500);

                flush();

                fixture.detectChanges();
                expect(element.innerText).toContain('tab-title-invisible');
            });
            tabWidgetComponent.tabChanged(null);
        }));

        it('should hide tab when it became not visible', fakeAsync(() => {
            fixture.detectChanges();

            tick(500);

            tabWidgetComponent.formTabChanged.subscribe((res) => {
                tabWidgetComponent.tabs[0].isVisible = false;

                tick(500);

                flush();

                fixture.detectChanges();
                expect(element.querySelector('innerText')).not.toContain('tab-title-visible');
            });
            tabWidgetComponent.tabChanged(null);
        }));

    });
开发者ID:Alfresco,项目名称:alfresco-ng2-components,代码行数:73,代码来源:tabs.widget.spec.ts

示例7: describe

describe("TagDetailComponent (inline template)", () => {
  let comp: TagDetailComponent;
  let fixture: ComponentFixture<TagDetailComponent>;
  let tagService: TagService;
  let userPermissionService: UserPermissionService;
  let scanningService: ScanningResultService;
  let spy: jasmine.Spy;
  let vulSpy: jasmine.Spy;
  let manifestSpy: jasmine.Spy;
  let mockVulnerability: VulnerabilitySummary = {
    scan_status: VULNERABILITY_SCAN_STATUS.finished,
    severity: 5,
    update_time: new Date(),
    components: {
      total: 124,
      summary: [
        {
          severity: 1,
          count: 90
        },
        {
          severity: 3,
          count: 10
        },
        {
          severity: 4,
          count: 10
        },
        {
          severity: 5,
          count: 13
        }
      ]
    }
  };
  let mockTag: Tag = {
    digest:
      "sha256:e5c82328a509aeb7c18c1d7fb36633dc638fcf433f651bdcda59c1cc04d3ee55",
    name: "nginx",
    size: "2049",
    architecture: "amd64",
    os: "linux",
    'os.version': "",
    docker_version: "1.12.3",
    author: "steven",
    created: new Date("2016-11-08T22:41:15.912313785Z"),
    signature: null,
    scan_overview: mockVulnerability,
    labels: []
  };

  let config: IServiceConfig = {
    repositoryBaseEndpoint: "/api/repositories/testing"
  };
  let mockHasVulnerabilitiesListPermission: boolean = false;
  let mockHasBuildHistoryPermission: boolean = true;
  let mockManifest: Manifest = {
    manifset: {},
    // tslint:disable-next-line:max-line-length
    config: `{"architecture":"amd64","config":{"Hostname":"","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["/bin/sh"],"ArgsEscaped":true,"Image":"sha256:fbef17698ac8605733924d5662f0cbfc0b27a51e83ab7d7a4b8d8a9a9fe0d1c2","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":null},"container":"30e1a2427aa2325727a092488d304505780501585a6ccf5a6a53c4d83a826101","container_config":{"Hostname":"30e1a2427aa2","Domainname":"","User":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["/bin/sh","-c","#(nop) ","CMD [\\"/bin/sh\\"]"],"ArgsEscaped":true,"Image":"sha256:fbef17698ac8605733924d5662f0cbfc0b27a51e83ab7d7a4b8d8a9a9fe0d1c2","Volumes":null,"WorkingDir":"","Entrypoint":null,"OnBuild":null,"Labels":{}},"created":"2018-01-09T21:10:58.579708634Z","docker_version":"17.06.2-ce","history":[{"created":"2018-01-09T21:10:58.365737589Z","created_by":"/bin/sh -c #(nop) ADD file:093f0723fa46f6cdbd6f7bd146448bb70ecce54254c35701feeceb956414622f in / "},{"created":"2018-01-09T21:10:58.579708634Z","created_by":"/bin/sh -c #(nop)  CMD [\\"/bin/sh\\"]","empty_layer":true}],"os":"linux","rootfs":{"type":"layers","diff_ids":["sha256:cd7100a72410606589a54b932cabd804a17f9ae5b42a1882bd56d263e02b6215"]}}`
  };
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [SharedModule],
      declarations: [
        TagDetailComponent,
        TagHistoryComponent,
        ResultGridComponent,
        VULNERABILITY_DIRECTIVES,
        LabelPieceComponent,
        FilterComponent
      ],
      providers: [
        ErrorHandler,
        ChannelService,
        JobLogDefaultService,
        { provide: JobLogService, useClass: JobLogDefaultService },
        { provide: SERVICE_CONFIG, useValue: config },
        { provide: TagService, useClass: TagDefaultService },
        { provide: UserPermissionService, useClass: UserPermissionDefaultService },
        {
          provide: ScanningResultService,
          useClass: ScanningResultDefaultService
        }
      ]
    });
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TagDetailComponent);
    comp = fixture.componentInstance;

    comp.tagId = "mock_tag";
    comp.repositoryId = "mock_repo";
    comp.projectId = 1;


    tagService = fixture.debugElement.injector.get(TagService);
    spy = spyOn(tagService, "getTag").and.returnValues(
      of(mockTag)
//.........这里部分代码省略.........
开发者ID:reasonerjt,项目名称:harbor,代码行数:101,代码来源:tag-detail.component.spec.ts

示例8: describe

    describe('Template transclusion', () => {

        @Component({
            selector: 'adf-test-component-for-sidenav',
            template: `
            <adf-sidenav-layout [sidenavMin]="70" [sidenavMax]="320" [stepOver]="600" [hideSidenav]="false">

                <adf-sidenav-layout-header>
                    <ng-template let-toggleMenu="toggleMenu">
                        <div id="header-test" (click)="toggleMenu()"></div>
                    </ng-template>
                </adf-sidenav-layout-header>

                <adf-sidenav-layout-navigation>
                    <ng-template let-isMenuMinimized="isMenuMinimized">
                        <div id="nav-test">{{ isMenuMinimized !== undefined ? 'variable-is-injected' : 'variable-is-not-injected' }}</div>
                    </ng-template>
                </adf-sidenav-layout-navigation>

                <adf-sidenav-layout-content>
                    <ng-template>
                        <div id="content-test"></div>
                    </ng-template>
                </adf-sidenav-layout-content>
            </adf-sidenav-layout>`
        })
        class SidenavLayoutTesterComponent {}

        beforeEach(async(() => {
            TestBed.configureTestingModule({ declarations: [ SidenavLayoutTesterComponent ] }).compileComponents();
        }));

        beforeEach(() => {
            mediaMatcher = TestBed.get(MediaMatcher);
            spyOn(mediaMatcher, 'matchMedia').and.returnValue(mediaQueryList);

            fixture = TestBed.createComponent(SidenavLayoutTesterComponent);
            fixture.detectChanges();
        });

        describe('adf-sidenav-layout-navigation', () => {

            const injectedElementSelector = By.css('[data-automation-id="adf-layout-container"] #nav-test');

            it('should contain the transcluded side navigation template', () => {
                const injectedElement = fixture.debugElement.query(injectedElementSelector);

                expect(injectedElement === null).toBe(false);
            });

            it('should let the isMenuMinimized property of component to be accessed by the transcluded template', () => {
                const injectedElement = fixture.debugElement.query(injectedElementSelector);

                expect(injectedElement.nativeElement.innerText.trim()).toBe('variable-is-injected');
            });
        });

        describe('adf-sidenav-layout-header', () => {

            const outerHeaderSelector = By.css('.adf-sidenav-layout > #header-test'),
                innerHeaderSelector = By.css('.adf-sidenav-layout [data-automation-id="adf-layout-container"] #header-test');

            it('should contain the transcluded header template outside of the layout-container', () => {
                mediaQueryList.matches = false;
                fixture.detectChanges();
                const outerHeaderElement = fixture.debugElement.query(outerHeaderSelector);
                const innerHeaderElement = fixture.debugElement.query(innerHeaderSelector);

                expect(outerHeaderElement === null).toBe(false, 'Outer header should be shown');
                expect(innerHeaderElement === null).toBe(true, 'Inner header should not be shown');
            });

            it('should contain the transcluded header template inside of the layout-container', () => {
                mediaQueryList.matches = true;
                fixture.detectChanges();
                const outerHeaderElement = fixture.debugElement.query(outerHeaderSelector);
                const innerHeaderElement = fixture.debugElement.query(innerHeaderSelector);

                expect(outerHeaderElement === null).toBe(true, 'Outer header should not be shown');
                expect(innerHeaderElement === null).toBe(false, 'Inner header should be shown');
            });

            it('should call through the layout container\'s toggleMenu method', () => {
                mediaQueryList.matches = false;
                fixture.detectChanges();
                const layoutContainerComponent = fixture.debugElement.query(By.directive(DummyLayoutContainerComponent)).componentInstance;
                spyOn(layoutContainerComponent, 'toggleMenu');

                const outerHeaderElement = fixture.debugElement.query(outerHeaderSelector);
                outerHeaderElement.triggerEventHandler('click', {});

                expect(layoutContainerComponent.toggleMenu).toHaveBeenCalled();
            });
        });

        describe('adf-sidenav-layout-content', () => {

            const injectedElementSelector = By.css('[data-automation-id="adf-layout-container"] #content-test');

            it('should contain the transcluded content template', () => {
//.........这里部分代码省略.........
开发者ID:Alfresco,项目名称:alfresco-ng2-components,代码行数:101,代码来源:sidenav-layout.component.spec.ts

示例9: describe

    describe('LogsComponent', () => {
        let comp: LogsComponent;
        let fixture: ComponentFixture<LogsComponent>;
        let service: LogsService;

        beforeEach(async(() => {
            TestBed.configureTestingModule({
                imports: [GatewayTestModule],
                declarations: [LogsComponent],
                providers: [LogsService]
            })
                .overrideTemplate(LogsComponent, '')
                .compileComponents();
        }));

        beforeEach(() => {
            fixture = TestBed.createComponent(LogsComponent);
            comp = fixture.componentInstance;
            service = fixture.debugElement.injector.get(LogsService);
        });

        describe('OnInit', () => {
            it('should set all default values correctly', () => {
                expect(comp.filter).toBe('');
                expect(comp.orderProp).toBe('name');
                expect(comp.reverse).toBe(false);
            });
            it('Should call load all on init', () => {
                // GIVEN
                const headers = new HttpHeaders().append('link', 'link;link');
                const log = new Log('main', 'WARN');
                spyOn(service, 'findAll').and.returnValue(
                    of(
                        new HttpResponse({
                            body: [log],
                            headers
                        })
                    )
                );

                // WHEN
                comp.ngOnInit();

                // THEN
                expect(service.findAll).toHaveBeenCalled();
                expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
            });
        });
        describe('change log level', () => {
            it('should change log level correctly', () => {
                // GIVEN
                const log = new Log('main', 'ERROR');
                spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse()));
                spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] })));

                // WHEN
                comp.changeLevel('main', 'ERROR');

                // THEN
                expect(service.changeLevel).toHaveBeenCalled();
                expect(service.findAll).toHaveBeenCalled();
                expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
            });
        });
    });
开发者ID:timofeev-denis,项目名称:Java,代码行数:65,代码来源:logs.component.spec.ts

示例10: describe

describe('Middleware Decorators', () => {

  let controller: MiddlewareController;

  beforeEach(() => {
    TestBed.configureTestingModule({ providers });
  });

  it('defines registeredMiddleware on the controller',
    inject([MiddlewareController, ReflectiveInjector, Server],
      (c: MiddlewareController, i: ReflectiveInjector, s: Server) => {

        controller = c.registerRoutes(s)
          .registerInjector(i);

        expect(controller.getMetadata().middleware)
          .not
          .toBeNull();
        expect(controller.getMetadata().middleware.all.before.length)
          .toEqual(2);
        expect(controller.getMetadata().middleware.all.after.length)
          .toEqual(1);
      }));

  it('adds middleware to the call stack',
    inject([MiddlewareController, ReflectiveInjector, Server],
      (c: MiddlewareController, i: ReflectiveInjector, s: Server) => {

        controller = c.registerRoutes(s)
          .registerInjector(i);

        const callStack: any = s.getRoutes()
          .reduce((middlewareStackMap: Object, route: RouteConfig) => {
            middlewareStackMap[route.methodName] = route.callStack.map((handler: PromiseFactory<Response>) => handler.name);
            return middlewareStackMap;
          }, {});

        expect(callStack.testMethod)
          .toEqual([
            'mockMiddleware',
            'mockMiddleware',
            'mockMiddleware',
            'testMethod',
            'mockMiddleware',
            'mockMiddleware'
          ]);

      }));

  it('calls the stack in the correct order defined by middleware',
    async(inject([MiddlewareController, ReflectiveInjector, Server],
      (c: MiddlewareController, i: ReflectiveInjector, s: Server) => {

        controller = c.registerRoutes(s)
          .registerInjector(i);

        const callStackHandler: any = s.getRoutes()
          .find((route: RouteConfig) => route.methodName == 'testMethod').callStackHandler;

        let request  = new Request();
        let response = new Response();

        return callStackHandler(request, response)
          .then(() => {

            expect(middlewareCalls)
              .toEqual([
                'one',
                'two',
                'three',
                'four',
                'five',
              ]);

          });

      })));

});
开发者ID:ubiquits,项目名称:ubiquits,代码行数:79,代码来源:middleware.spec.ts


注:本文中的@angular/core/testing.async函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。