@angular/platform-browser#By TypeScript Examples

The following examples show how to use @angular/platform-browser#By. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: focus.directive.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('LgFocusDirective', () => {
  let component: TestFocusComponent;
  let fixture: ComponentFixture<TestFocusComponent>;
  let el: HTMLElement;
  let focusSpy: jasmine.Spy;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ TestFocusComponent, LgFocusDirective ],
    });

    fixture = TestBed.createComponent(TestFocusComponent);
    component = fixture.componentInstance;
    const de = fixture.debugElement.query(By.css('button'));

    el = de.nativeElement;
    focusSpy = spyOn(el, 'focus');
  });

  describe('when the directive is set to "true"', () => {
    it('should set focus on the element', () => {
      component.testVar = true;
      fixture.detectChanges();

      expect(focusSpy).toHaveBeenCalled();
    });
  });

  describe('when the directive is set to "false"', () => {
    it('should not set focus on the element', () => {
      component.testVar = false;
      fixture.detectChanges();

      expect(focusSpy).not.toHaveBeenCalled();
    });
  });
});
Example #2
Source File: accordion.component.spec.ts    From alauda-ui with MIT License 6 votes vote down vote up
describe('AccordionComponent', () => {
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [AccordionModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
  });

  it('should render correct construction', () => {
    fixture.detectChanges();
    const accordionItemHeaderEl = fixture.debugElement.query(
      By.css('.aui-accordion-item__expand-button'),
    ).nativeElement as HTMLElement;
    expect(accordionItemHeaderEl).not.toBeNull();
    expect(
      accordionItemHeaderEl.querySelector('use').getAttribute('xlink:href'),
    ).toBe('#aui-icon-angle_right');
  });

  it('accordion item content show when click icon', () => {
    fixture.detectChanges();
    const accordionItemHeaderEl = fixture.debugElement.query(
      By.css('.aui-accordion-item__header'),
    ).nativeElement as HTMLElement;
    accordionItemHeaderEl.dispatchEvent(new Event('click'));

    fixture.detectChanges();
    const accordionContentBody = fixture.debugElement.query(
      By.css('.aui-accordion-item__content'),
    );
    expect(accordionContentBody).toBeFalsy();
  });
});
Example #3
Source File: app.component.spec.ts    From angular-padroes-e-boas-praticas with MIT License 6 votes vote down vote up
describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ AppComponent, HeaderComponent ],
      imports: [ RouterTestingModule ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it(`should have as title 'TODO APP'`, () => {
    expect(component.title).toEqual('TODO APP');
  });

  it(`should contain a header with title`, () => {
    const headerComponent: HeaderComponent = fixture.debugElement.query(
      By.directive(HeaderComponent)
    ).componentInstance;
    expect(headerComponent).toBeTruthy();
    expect(headerComponent.title).toBe('TODO APP');
  });

});
Example #4
Source File: ngx-tippy-group.spec.ts    From ngx-tippy-wrapper with MIT License 6 votes vote down vote up
describe('Component: NgxTippyGroupComponent (wrapped)', () => {
  let injector: TestBed;
  let fixture: ComponentFixture<TestWrapperComponent>;
  let component: TestWrapperComponent;
  let debugEl: DebugElement;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      declarations: [NgxTippyGroupComponent, TestWrapperComponent],
      providers: [
        {
          provide: NGX_TIPPY_MESSAGES,
          useValue: messagesDict,
        },
      ],
    })
      .compileComponents()
      .then(() => {
        injector = getTestBed();
        fixture = injector.createComponent(TestWrapperComponent);
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
        fixture.detectChanges();
      });
  });

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

  it('should render all grouped elements', () => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));

    expect(groupEls).toBeTruthy();
    expect(groupEls.length).toBe(3);
  });

  it('should show tooltips on click', () => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));
    groupEls.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('click'));
    });
    fixture.detectChanges();
    const tooltips = fixture.debugElement.queryAll(By.css('div[data-tippy-root]'));

    expect(tooltips).toBeTruthy();
    expect(tooltips.length).toBe(3);
  });

  it('should apply properties', fakeAsync(() => {
    const groupEls = debugEl.queryAll(By.css('button[data-tippy-grouped]'));
    groupEls.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('click'));
    });
    fixture.detectChanges();

    const tooltipArrow = fixture.debugElement.queryAll(By.css('.tippy-arrow'));
    const tippyBox = fixture.debugElement.queryAll(By.css('.tippy-box'));
    const tooltipBgColor = getComputedStyle(tippyBox[1].nativeElement).backgroundColor;

    expect(tooltipArrow[0]).toBeUndefined();
    expect(tooltipBgColor).toBe('rgb(255, 255, 255)');

    let dataPlacement!: string;
    setTimeout(() => {
      dataPlacement = tippyBox[2].nativeElement.dataset.placement;
    }, 0);

    tick(0);

    expect(dataPlacement).toBe('bottom');
  }));
});
Example #5
Source File: upload-data-rules.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
describe('UploadDataRulesComponent', () => {
  let component: UploadDataRulesComponent
  let fixture: ComponentFixture<UploadDataRulesComponent>

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [TranslateModule.forRoot()],
      declarations: [UploadDataRulesComponent],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(UploadDataRulesComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

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

  it('should display accepted file formats', () => {
    const el = fixture.debugElement.query(By.css('.formats')).nativeElement

    expect(el.childElementCount).toEqual(component.acceptedFileFormats.length)

    const childArr = [...el.children]
    childArr.forEach((c) => {
      expect(
        component.acceptedFileFormats.find((f) =>
          f.localeCompare(c.textContent.replace('- ', ''))
        )
      ).toBeTruthy()
    })

    expect(component).toBeTruthy()
  })
})
Example #6
Source File: injectable-superclass.spec.ts    From s-libs with MIT License 6 votes vote down vote up
describe('InjectableSuperclass', () => {
  let ctx: TestComponentContext;
  beforeEach(async () => {
    ctx = new TestComponentContext();
  });

  it('cleans up subscriptions when destroyed by angular', () => {
    ctx.run(() => {
      expect(ctx.subject.observers.length).toBe(2);

      ctx.getComponentInstance().showThings = false;
      ctx.fixture.detectChanges();
      expect(ctx.subject.observers.length).toBe(0);
    });
  });

  it('has .destruction$ which emits and completes upon destruction', () => {
    const next = jasmine.createSpy();
    const complete = jasmine.createSpy();
    ctx.run(() => {
      const host = ctx.fixture.debugElement.query(
        By.directive(DestroyableDirective),
      );
      const service = host.injector.get(DestroyableService);
      service.destruction$.subscribe({ next, complete });

      ctx.getComponentInstance().showThings = false;
      ctx.fixture.detectChanges();
      expectSingleCallAndReset(next, undefined);
      expectSingleCallAndReset(complete);
    });
  });
});
Example #7
Source File: app.component.spec.ts    From 6PG-Dashboard with MIT License 6 votes vote down vote up
describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [ HttpClientModule ]
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it('should have a router outlet', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const routerOutlet = fixture.debugElement.query(By.directive(RouterOutlet));  
    expect(routerOutlet?.nativeElement).toBeTruthy();
  });
});
Example #8
Source File: ngx-mat-autofocus.directive.spec.ts    From ngx-mat-timepicker with MIT License 6 votes vote down vote up
describe("AutofocusDirective", () => {
    let component: TestComponent;
    let fixture: ComponentFixture<TestComponent>;
    let debugElement: DebugElement;
    let directive: NgxMatTimepickerAutofocusDirective;

    beforeEach(() => {
        fixture = TestBed.configureTestingModule({
            declarations: [TestComponent, NgxMatTimepickerAutofocusDirective],
            schemas: [NO_ERRORS_SCHEMA]
        }).createComponent(TestComponent);

        component = fixture.componentInstance;
        debugElement = fixture.debugElement.query(By.directive(NgxMatTimepickerAutofocusDirective));
        directive = debugElement.injector.get(NgxMatTimepickerAutofocusDirective);
        fixture.detectChanges();
    });

    it("should focus element on which directive is applied", fakeAsync(() => {
        expect(document.activeElement).toEqual(document.body);
        directive.ngOnChanges();
        tick();
        expect(document.activeElement).toEqual(debugElement.nativeElement);
    }));

    it("should not focus element on which directive is applied", fakeAsync(() => {
        directive.isFocusActive = false;
        expect(document.activeElement).toEqual(document.body);
        directive.ngOnChanges();
        tick();
        expect(document.activeElement).toEqual(document.body);
    }));
});
Example #9
Source File: bar.component.spec.ts    From ngx-gantt with MIT License 6 votes vote down vote up
describe('ngx-gantt-bar', () => {
    let fixture: ComponentFixture<TestGanttBarComponent>;
    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [CommonModule, NgxGanttModule],
            declarations: [TestGanttBarComponent]
        }).compileComponents();
        fixture = TestBed.createComponent(TestGanttBarComponent);
        fixture.detectChanges();
    });

    it('should has bar progress', () => {
        const barProgress = fixture.debugElement.queryAll(By.css('.gantt-bar-content-progress'));
        expect(barProgress.length).toEqual(1);
    });
});
Example #10
Source File: block-card.component.spec.ts    From slate-angular with MIT License 6 votes vote down vote up
describe('Block Card Component', () => {
    let component: ImageEditableComponent;
    let fixture: ComponentFixture<ImageEditableComponent>;

    beforeEach(fakeAsync(() => {
        configureBasicEditableTestingModule([ImageEditableComponent]);
        fixture = TestBed.createComponent(ImageEditableComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        flush();
        fixture.detectChanges();
    }));    

    it('The block-card component should be created', fakeAsync(() => {
        let blockCardElement: HTMLElement;
        blockCardElement = fixture.debugElement.query(By.css('.slate-block-card')).nativeElement;
        expect(blockCardElement).toBeTruthy();
    }));
});
Example #11
Source File: context-selector.component.spec.ts    From one-platform with MIT License 5 votes vote down vote up
describe('ContextSelectorComponent', () => {
  let component: ContextSelectorComponent;
  let fixture: ComponentFixture<ContextSelectorComponent>;

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

  beforeEach(() => {
    fixture = TestBed.createComponent(ContextSelectorComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('default values for context select', () => {
    expect(component.isOpen).toBeFalsy();
    expect(component.searchInputValue).toBe('');
    expect(component.toggleText).toBe('');
  });

  it('should be hidden', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const el = fixture.debugElement.query(
        By.css('.pf-c-context-selector__menu')
      );
      expect(el).toBeNull();
    });
  });

  it('should reveal options', fakeAsync(() => {
    component.isOpen = true;
    tick();
    fixture.detectChanges();
    expect(component.isOpen).toBeTruthy();
    const el = fixture.debugElement.query(
      By.css('.pf-c-context-selector__menu')
    );
    expect(el).toBeTruthy();
  }));
});
Example #12
Source File: login-dialog.component.spec.ts    From ng-conf-2020-workshop with MIT License 5 votes vote down vote up
describe('LoginDialogComponent', () => {
  let component: LoginDialogComponent;
  let fixture: ComponentFixture<LoginDialogComponent>;

  const checkViews = (login, register) => {
    const loginView = fixture.debugElement.query(By.css('app-login'));
    const registerView = fixture.debugElement.query(By.css('app-register'));
    expect(loginView).toEqual(login);
    expect(registerView).toEqual(register);
  };

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginDialogComponent, TestSignViewComponent ],
      imports: [ NoopAnimationsModule, IgxDialogModule ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginDialogComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should switch views, show login on open', () => {
    checkViews(jasmine.any(DebugElement), null);
    component.showLogin = false;
    fixture.detectChanges();
    checkViews(null, jasmine.any(DebugElement));
    expect(component.loginDialog.title).toEqual('Register');
    component.open();
    fixture.detectChanges();
    checkViews(jasmine.any(DebugElement), null);
    expect(component.showLogin).toBeTruthy();
    expect(component.loginDialog.title).toEqual('Login');
  });

  it('should switch views, close on events', () => {
    let view: TestSignViewComponent = fixture.debugElement.query(By.css('app-login')).componentInstance;
    spyOn(component.loginDialog, 'close');

    view.viewChange.emit();
    expect(component.showLogin).toBeFalsy();
    view.loggedIn.emit();
    expect(component.loginDialog.close).toHaveBeenCalledTimes(1);
    fixture.detectChanges();
    view = fixture.debugElement.query(By.css('app-register')).componentInstance;
    view.viewChange.emit();
    expect(component.showLogin).toBeTruthy();
    view.registered.emit();
    expect(component.loginDialog.close).toHaveBeenCalledTimes(2);
  });
});
Example #13
Source File: accordion.component.spec.ts    From canopy with Apache License 2.0 5 votes vote down vote up
describe('LgAccordionComponent', () => {
  let component: TestAccordionComponent;
  let fixture: ComponentFixture<TestAccordionComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestAccordionComponent,
        LgAccordionComponent,
        LgAccordionItemComponent,
        LgAccordionItemContentDirective,
        LgAccordionPanelHeadingComponent,
        MockComponents(LgHeadingComponent, LgIconComponent),
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestAccordionComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should set the heading level on the panel headings', () => {
    fixture.debugElement
      .queryAll(By.css('lg-accordion-panel-heading'))
      .forEach(heading => {
        expect(
          heading.injector.get<LgAccordionPanelHeadingComponent>(
            LgAccordionPanelHeadingComponent,
          ).headingLevel,
        ).toBe(2);
      });
  });

  describe('when using single item active view', () => {
    let itemOne: DebugElement;
    let itemTwo: DebugElement;

    beforeEach(() => {
      component.isMulti = false;
      fixture.detectChanges();

      const items = fixture.debugElement.queryAll(By.css('lg-accordion-item'));

      itemOne = items[0];
      itemTwo = items[1];
    });

    it('should toggle the active open panel', () => {
      expect(itemOne.componentInstance.isActive).toBeFalsy();
      expect(itemTwo.componentInstance.isActive).toBeTruthy();

      itemOne.nativeElement.querySelector('.lg-accordion__heading-toggle').click();
      fixture.detectChanges();

      expect(itemOne.componentInstance.isActive).toBeTruthy();
      expect(itemTwo.componentInstance.isActive).toBeFalsy();
    });
  });
});
Example #14
Source File: highlight.directive.spec.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
describe('HighlightDirective', () => {
  it('When calling onMouseEnterEvent(), the element is highlighted', () => {
    const p = document.createElement('p');
    const element = new ElementRef(p);
    const directive = new HighlightDirective(element);
    directive['color'] = 'orange';
    directive.onMouseEnterEvent();

    expect(element.nativeElement.style.backgroundColor).toBe('orange');
  });

  it('When calling onMouseLeave(), the element is un-highlighted', () => {
    const p = document.createElement('p');
    const element = new ElementRef(p);
    const directive = new HighlightDirective(element);
    directive['color'] = 'orange';
    directive.onMouseEnterEvent();
    directive.onMouseLeaveEvent();

    expect(element.nativeElement.style.backgroundColor).toBe('');
  });

  it('Probando la directiva en el DOM', () => {
    const fixture: ComponentFixture<TestComponent> = TestBed.configureTestingModule({
      declarations: [ HighlightDirective, TestComponent ]
    })
    .createComponent(TestComponent);

    fixture.detectChanges(); // Forzamos detección de cambios para hacer el binding inicial

    // Array de elementos a los que se le aplica la direciva
    const elems = fixture.debugElement.queryAll(By.directive(HighlightDirective));

    expect(elems.length).toBe(2);

    // Primer h2
    elems[0].nativeElement.dispatchEvent(new Event('mouseenter'));
    fixture.detectChanges();
    const bgColorEnter = elems[0].nativeElement.style.backgroundColor;
    expect(bgColorEnter).toBe('yellow');

    elems[0].nativeElement.dispatchEvent(new Event('mouseleave'));
    fixture.detectChanges();
    const bgColorLeave = elems[0].nativeElement.style.backgroundColor;
    expect(bgColorLeave).toBe('');

    // Este es el h2 al que no se aplica la directiva
    const bareH2 = fixture.debugElement.query(By.css('h2:not([appHighlight])'));
    bareH2.nativeElement.dispatchEvent(new Event('mouseenter'));
    fixture.detectChanges();
    const bgColorbareH2 = bareH2.nativeElement.style.backgroundColor;
    expect(bgColorbareH2).toBe('');

  });
});
Example #15
Source File: landing.component.spec.ts    From TheHungryRecipesApp with GNU General Public License v3.0 5 votes vote down vote up
describe('LandingComponent', () => {
  let component: LandingComponent;
  let fixture: ComponentFixture<LandingComponent>;
  let debugElement: DebugElement;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
        RouterTestingModule.withRoutes([
          {path: 'recipelist', loadChildren: () => import('../../components/recipelist/recipelist.module').then(m => m.RecipelistModule)}
        ]),
        MatIconModule
      ],
      declarations: [ LandingComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LandingComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    fixture.detectChanges();
  });

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

  it('should have search recipe button', () => {
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('a.btnSearchRecipe')).toBeTruthy();
  });

  it('should have random recipe button', () => {
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('a.btnRandomRecipe')).toBeTruthy();
  });

  it('should have page description', () => {
    let heading = fixture.nativeElement.querySelector('h4');
    expect(heading.textContent).toBeTruthy();
  });

  it('should fail when search value is undefined', () => {
    let inputValue = debugElement.query(By.css('input'));
    component.recipeName = undefined;
    inputValue.triggerEventHandler('keyup',component.navigate());
    fixture.detectChanges();
    let errorValue = debugElement.query(By.css('label')).nativeElement.textContent;
    expect(errorValue).toBeTruthy();
  });

  it('should navigate when search value is valid', () => {
    let inputValue = debugElement.query(By.css('input'));
    component.recipeName = 'BEEF';
    inputValue.triggerEventHandler('keyup',component.navigate());
    fixture.detectChanges();
    let errorElement = debugElement.query(By.css('label'));
    expect(errorElement).toBeNull();
    expect(component.inputError).toEqual(false);
  });

});
Example #16
Source File: status.component.spec.ts    From visualization with MIT License 5 votes vote down vote up
describe('StatusComponent', () => {
  let statusComponent: StatusComponent;
  let dataStudioService: DataStudioService;
  let fixture: ComponentFixture<StatusComponent>;

  const statusSubject$ = new Subject<Status>();

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [StatusComponent],
      imports: [AppTestingModule],
    })
      .compileComponents();
  });

  beforeEach(() => {
    dataStudioService = TestBed.inject(DataStudioService);
    spyOnProperty(dataStudioService, 'Status$').and.returnValue(statusSubject$);
    fixture = TestBed.createComponent(StatusComponent);
    statusComponent = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(statusComponent).toBeTruthy();
  });
  it('should show message for GettingTableData', () => {
    statusSubject$.next(Status.GettingTableData);
    expect(getById('Status-GettingTableData')).toBeTruthy();
  });
  it('should show message for GeneratingSvg', () => {
    statusSubject$.next(Status.GeneratingSvg);
    expect(getById('Status-GeneratingSvg')).toBeTruthy();
  });

  it('should show message for BuildingChart', () => {
    statusSubject$.next(Status.BuildingChart);
    expect(getById('Status-BuildingChart')).toBeTruthy();
  });

  it('should show loading when no status', () => {
    expect(getById('Loading')).toBeTruthy();
  });

  it('should not show loading when status', () => {
    statusSubject$.next(Status.Complete);
    expect(getById('Loading')).toBeFalsy();
  });

  [
    Status.Complete,
    Status.NoDatabase,
    Status.Error].forEach((status: Status) => it(`should not show anything when status is ${status}`, () => {
      statusSubject$.next(Status.Complete);
      expect(getById('Empty')).toBeTruthy();
    }));

  const getById = (id: string) => {
    fixture.detectChanges();
    return fixture.debugElement.query(By.css('#' + id));
  };
});
Example #17
Source File: checkbox-group.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('CheckboxGroupComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let el1: HTMLElement;
  let el2: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule, CheckboxModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    el1 = fixture.debugElement.query(
      By.css('.group1 aui-checkbox-group'),
    ).nativeElement;
    el2 = fixture.debugElement.query(
      By.css('.group2 aui-checkbox-group'),
    ).nativeElement;
  });

  it('should checkbox init checked state by value array', fakeAsync(() => {
    ins.value = ['box1', 'box2', 'box3'];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    const boxes = el1.querySelectorAll('.aui-checkbox');
    expect(boxes.item(0).className).not.toContain('isChecked');
    expect(boxes.item(1).className).toContain('isChecked');
    expect(boxes.item(2).className).toContain('isChecked');
    expect(boxes.item(3).className).toContain('isChecked');
  }));

  it('should value change when checkbox clicked', () => {
    const boxes = el1.querySelectorAll('.aui-checkbox input');
    boxes.item(0).dispatchEvent(new Event('click'));
    boxes.item(1).dispatchEvent(new Event('click'));
    boxes.item(2).dispatchEvent(new Event('click'));
    boxes.item(3).dispatchEvent(new Event('click'));
    fixture.detectChanges();

    expect(ins.value).toEqual(['box0', 'box1', 'box2']);
  });

  it('should checkbox init checked state by collection', fakeAsync(() => {
    ins.value2 = [{ name: 'box2' }];
    fixture.detectChanges();
    tick();
    fixture.detectChanges();

    const boxes = el2.querySelectorAll('.aui-checkbox');
    expect(boxes.item(0).className).not.toContain('isChecked');
    expect(boxes.item(1).className).toContain('isChecked');
    expect(boxes.item(2).className).not.toContain('isChecked');
  }));
});
Example #18
Source File: todo-add-form.component.spec.ts    From angular-padroes-e-boas-praticas with MIT License 5 votes vote down vote up
describe('TodoAddFormComponent', () => {
  let component: TodoAddFormComponent;
  let fixture: ComponentFixture<TodoAddFormComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ TodoAddFormComponent ],
      imports: [ ReactiveFormsModule ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TodoAddFormComponent);
    component = fixture.componentInstance;
    component.todoAddForm = new FormControl();
  });

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

  it('todoAddForm should be valid', () => {
    expect(component.todoAddForm).toBeTruthy();
  });

  it('button should be disabled when todoAddForm is invalid', () => {
    component.todoAddForm = new FormControl();
    component.todoAddForm.setErrors({ incorrect: true });
    fixture.detectChanges();

    const buttonElement: HTMLElement = fixture.debugElement.query(By.css('button')).nativeElement;

    let value: string = null;
    component.addTodo.subscribe(response => value = response);
    buttonElement.click();
    expect(value).toBeFalsy();
  });


  it('should emit value on click addTodo', () => {
    component.todoAddForm = new FormControl('text');
    fixture.detectChanges();
    const buttonElement: HTMLElement = fixture.debugElement.query(By.css('button')).nativeElement;
    let value: string = null;
    component.addTodo.subscribe(response => value = response);
    buttonElement.click();
    expect(value).toBe('text');
  });
});
Example #19
Source File: drawer-header.component.spec.ts    From angular-component-library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
describe('DrawerHeaderComponent', () => {
    let component: DrawerHeaderComponent;
    let fixture: ComponentFixture<DrawerHeaderComponent>;

    beforeEach(() => {
        void TestBed.configureTestingModule({
            declarations: [TestDrawerHeader, TestDrawerHeaderWithTitleContent, TestDrawerHeaderWithIcon],
            imports: [DrawerHeaderModule, MatIconModule],
        }).compileComponents();
        fixture = TestBed.createComponent(DrawerHeaderComponent);
        component = fixture.componentInstance;
        spyOn(component, 'ngOnInit').and.stub();
        spyOn(component, 'ngOnDestroy').and.stub();
    });

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

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

    it('should render title', () => {
        component.title = 'test title';
        fixture.detectChanges();
        const title = fixture.debugElement.query(By.css('.blui-drawer-header-title'));
        void expect(title.nativeElement.innerHTML.trim()).toBe('test title');
    });

    it('should render subtitle', () => {
        component.title = 'test title';
        component.subtitle = 'test subtitle';
        fixture.detectChanges();
        const subtitle = fixture.debugElement.query(By.css('.blui-drawer-header-subtitle'));
        void expect(subtitle.nativeElement.innerHTML.trim()).toBe('test subtitle');
    });

    it('should render titleContent', () => {
        const customFixture = TestBed.createComponent(TestDrawerHeaderWithTitleContent);
        customFixture.detectChanges();
        const content: HTMLElement = customFixture.nativeElement.querySelector('#test-title-content');
        void expect(content.innerHTML).toBe('test title content');
    });

    it('should render icon', () => {
        const customFixture = TestBed.createComponent(TestDrawerHeaderWithIcon);
        customFixture.detectChanges();
        const icon: HTMLElement = customFixture.nativeElement.querySelector('#test-icon');
        void expect(icon.innerHTML).toBe(
            '<mat-icon role="img" class="mat-icon notranslate material-icons mat-icon-no-color" aria-hidden="true" data-mat-icon-type="font">menu</mat-icon>'
        );
    });

    it('should enforce class naming conventions', () => {
        const customFixture = TestBed.createComponent(TestDrawerHeader);
        customFixture.detectChanges();
        const classList = [
            '.blui-drawer-header',
            '.blui-drawer-header-content',
            '.blui-drawer-header-background',
            '.blui-drawer-header-content',
            '.blui-drawer-header-icon-wrapper',
            '.blui-drawer-header-title-wrapper',
            '.blui-drawer-header-title',
            '.blui-drawer-header-subtitle',
        ];
        for (const className of classList) {
            count(customFixture, className);
        }
    });
});
Example #20
Source File: ngx-tippy-singleton.spec.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
describe('Component: NgxTippySingletonComponent (wrapped)', () => {
  let injector: TestBed;
  let fixture: ComponentFixture<TestWrapperComponent>;
  let component: TestWrapperComponent;
  let debugEl: DebugElement;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      declarations: [NgxTippyDirective, NgxTippySingletonComponent, TestWrapperComponent],
      providers: [
        NgxTippyService,
        {
          provide: NGX_TIPPY_MESSAGES,
          useValue: messagesDict,
        },
      ],
    })
      .compileComponents()
      .then(() => {
        injector = getTestBed();
        fixture = injector.createComponent(TestWrapperComponent);
        component = fixture.componentInstance;
        debugEl = fixture.debugElement;
        fixture.detectChanges();
      });
  });

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

  it('should render all grouped elements', () => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));

    expect(singletonItems).toBeTruthy();
    expect(singletonItems.length).toBe(3);
  });

  it('should show tooltips on hover', () => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));
    singletonItems.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('mouseenter'));
    });
    fixture.detectChanges();
    const tooltips = fixture.debugElement.queryAll(By.css('div[data-tippy-root]'));

    expect(tooltips).toBeTruthy();
    expect(tooltips.length).toBe(1);
  });

  it('should apply properties', fakeAsync(() => {
    const singletonItems = debugEl.queryAll(By.css('button[data-tippy-singleton]'));
    singletonItems.forEach(el => {
      el.nativeElement.dispatchEvent(new MouseEvent('mouseenter'));
    });
    fixture.detectChanges();

    const tooltipArrow = fixture.debugElement.query(By.css('.tippy-arrow'));
    const tippyBox = fixture.debugElement.query(By.css('.tippy-box'));
    const tooltipBgColor = getComputedStyle(tippyBox.nativeElement).backgroundColor;

    expect(tooltipArrow).toBeNull();
    expect(tooltipBgColor).toBe('rgb(255, 255, 255)');

    let dataPlacement!: string;

    setTimeout(() => {
      dataPlacement = tippyBox.nativeElement.dataset.placement;
    }, 0);
    tick(0);

    expect(dataPlacement).toBe('top');
  }));
});
Example #21
Source File: data-import-validation-map-panel.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 5 votes vote down vote up
describe('MapViewComponent', () => {
  let component: DataImportValidationMapPanelComponent
  let fixture: ComponentFixture<DataImportValidationMapPanelComponent>

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [UtilI18nModule, TranslateModule.forRoot()],
      declarations: [DataImportValidationMapPanelComponent],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: { params: of({ id: 1 }) },
        },
      ],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(DataImportValidationMapPanelComponent)
    component = fixture.componentInstance
    component.headerLabel = 'title'
    component.geoJson = {
      type: 'Feature',
      properties: {
        id: '0',
      },
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [100.0, 0.0],
            [101.0, 0.0],
            [101.0, 1.0],
            [100.0, 1.0],
            [100.0, 0.0],
          ],
        ],
      },
    }

    fixture.detectChanges()
  })

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

  it('should display head title', () => {
    const el = fixture.debugElement.query(By.css('.header-label')).nativeElement
    expect(el.textContent).toEqual(' title ')
  })
})
Example #22
Source File: big-input-action.component.spec.ts    From enterprise-ng-2020-workshop with MIT License 5 votes vote down vote up
describe('BigInputActionComponent', () => {
  let component: HostComponent;
  let fixture: ComponentFixture<HostComponent>;

  const getButton = () => fixture.debugElement.query(By.css('button'));
  const getIcon = () => fixture.debugElement.query(By.css('mat-icon'));
  const getLabel = () =>
    fixture.debugElement.query(By.css('.mat-button-wrapper > span'));

  function createHostComponent(
    template: string
  ): ComponentFixture<HostComponent> {
    TestBed.overrideComponent(HostComponent, { set: { template: template } });
    fixture = TestBed.createComponent(HostComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    return fixture;
  }

  beforeEach(() =>
    TestBed.configureTestingModule({
      declarations: [HostComponent],
      imports: [SharedModule, NoopAnimationsModule]
    })
  );

  it('should be created', () => {
    const template = '<mfework-big-input-action></mfework-big-input-action>';
    fixture = createHostComponent(template);
    expect(component).toBeTruthy();
  });

  it('should initially not be disabled and show no icon or label', () => {
    const template = '<mfework-big-input-action></mfework-big-input-action>';
    fixture = createHostComponent(template);
    expect(getButton().nativeElement.disabled).toBeFalsy();
    expect(getIcon()).toBeNull();
    expect(getLabel()).toBeNull();
  });

  it('should disable button if disabled property is set', () => {
    const template =
      '<mfework-big-input-action [disabled]="true"></mfework-big-input-action>';
    fixture = createHostComponent(template);
    expect(getButton().nativeElement.disabled).toBeTruthy();
  });

  it('should display icon if fontSet and fontIcon properties are set', () => {
    const template = `<mfework-big-input-action fontSet="fas" fontIcon="fa-trash"></mfework-big-input-action>`;
    fixture = createHostComponent(template);
    expect(getIcon()).toBeTruthy();
    expect(getIcon().nativeElement.classList.contains('fa-trash')).toBeTruthy();
    expect(getIcon().nativeElement.classList.contains('fas')).toBeTruthy();
  });

  it('should display label with provided text when label property is set', () => {
    const template = `<mfework-big-input-action label="delete"></mfework-big-input-action>`;
    fixture = createHostComponent(template);
    expect(getLabel()).toBeTruthy();
    expect(getLabel().nativeElement.textContent).toBe('delete');
  });

  it('should emit action event on button click', () => {
    const template = `<mfework-big-input-action (action)="actionHandler()"></mfework-big-input-action>`;
    fixture = createHostComponent(template);
    spyOn(component, 'actionHandler').and.callThrough();
    getButton().triggerEventHandler('click', {});
    expect(component.actionHandler).toHaveBeenCalled();
  });
});
Example #23
Source File: nas-model.directive.spec.ts    From s-libs with MIT License 5 votes vote down vote up
function queryAll(css: string): any[] {
  return fixture.debugElement
    .queryAll(By.css(css))
    .map((el) => el.nativeElement);
}
Example #24
Source File: customize-xp-card.component.spec.ts    From 6PG-Dashboard with MIT License 5 votes vote down vote up
describe('CustomizeXPCardComponent', () => {
  let component: CustomizeXPCardComponent;
  let fixture: ComponentFixture<CustomizeXPCardComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomizeXPCardComponent ],
      imports: [ HttpClientModule, FormsModule, ReactiveFormsModule ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CustomizeXPCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('on value change, xp card preview is updated', () => {
    const spy = spyOn(component, 'updatePreview').and.callThrough();

    component.form.get('primary').setValue('123');

    expect(spy).toHaveBeenCalled();
  });

  it('click button, submits form', () => {
    const spy = spyOn(component, 'submit').and.callThrough();
    const de = fixture.debugElement.query(By.css('#submit'));
    
    de.nativeElement.click();

    expect(spy).toHaveBeenCalled();
  });

  it('click stock image, setBackground is called', () => {
    const spy = spyOn(component, 'setBackground').and.callThrough();
    const de = fixture.debugElement.query(By.css('.stock-image'));

    de?.nativeElement.click();

    expect(spy).toHaveBeenCalled();
  });

  it('click stock image, updatePreview is called', () => {
    const spy = spyOn(component, 'updatePreview').and.callThrough();
    const de = fixture.debugElement.query(By.css('.stock-image'));

    de?.nativeElement.click();

    expect(spy).toHaveBeenCalled();
  });
});