@angular/core#DebugElement TypeScript Examples

The following examples show how to use @angular/core#DebugElement. 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: data-point-value.component.spec.ts    From canopy with Apache License 2.0 6 votes vote down vote up
describe('LgDataPointValueComponent', () => {
  let component: LgDataPointValueComponent;
  let fixture: ComponentFixture<LgDataPointValueComponent>;
  let debugElement: DebugElement;
  let el: HTMLElement;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ LgDataPointValueComponent ],
      }).compileComponents();
    }),
  );

  beforeEach(() => {
    fixture = MockRender(`
    <lg-data-point-value>
      Joe Bloggs
    </lg-data-point-value>
    `);

    debugElement = fixture.debugElement;
    component = fixture.componentInstance;
    el = debugElement.children[0].nativeElement;
    fixture.detectChanges();
  });

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

  it('should have the default class', () => {
    expect(el.getAttribute('class')).toContain('lg-data-point-value');
  });

  it('should render the heading', () => {
    expect(el.innerHTML).toContain('Joe Bloggs');
  });
});
Example #2
Source File: input.component.spec.ts    From alauda-ui with MIT License 6 votes vote down vote up
describe('InputComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [InputModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('input'));
    el = debugEl.nativeElement;
  });

  it('should render correct class', () => {
    expect(el.className).toContain('aui-input');
    expect(el.className).toContain('aui-input--medium');
  });

  it('should size option work correctly', () => {
    ins.size = ComponentSize.Mini;
    fixture.detectChanges();
    expect(el.className).toContain('aui-input--mini');
  });
});
Example #3
Source File: card.component.spec.ts    From angular-padroes-e-boas-praticas with MIT License 6 votes vote down vote up
describe('CardComponent', () => {
  let component: CardComponent;
  let fixture: ComponentFixture<CardComponent>;

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

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

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

  it('should show ng-content content', () => {
    const testFixture = TestBed.createComponent(TestHostComponent);

    const de: DebugElement = testFixture.debugElement.query(By.css('fieldset'));
    const el: HTMLElement = de.nativeElement;

    expect(el.textContent).toEqual('Hello World');
  });
});
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: facet-block.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 6 votes vote down vote up
describe('EmptyFacetBlockComponent', () => {
  let component: FacetBlockComponent
  let fixture: ComponentFixture<FacetBlockComponent>
  let de: DebugElement

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [FacetBlockComponent, FacetItemStubComponent],
      imports: [FormsModule, TranslateModule.forRoot()],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(FacetBlockComponent)
    component = fixture.componentInstance
    de = fixture.debugElement
    component.model = EMPTY_BLOCK_MODEL_FIXTURE
    component.selectedPaths = []
    fixture.detectChanges()
  })

  describe('Aggregation is hidden if no item', () => {
    it('hides aggregation', () => {
      expect(de.query(By.css('div > span'))).toBeFalsy()
      expect(component.hasItems).toBe(false)
    })
  })
})
Example #6
Source File: card.component.spec.ts    From dayz-server-manager with MIT License 6 votes vote down vote up
describe('CardComponent', () => {
    let fixture: ComponentFixture<TestHostComponent>;
    let hostComponent: TestHostComponent;
    let hostComponentDE: DebugElement;
    let hostComponentNE: Element;

    let component: CardComponent;
    let componentDE: DebugElement;
    let componentNE: Element;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestHostComponent, CardComponent],
            imports: [NoopAnimationsModule],
            providers: [],
            schemas: [NO_ERRORS_SCHEMA],
        }).compileComponents();

        fixture = TestBed.createComponent(TestHostComponent);
        hostComponent = fixture.componentInstance;
        hostComponentDE = fixture.debugElement;
        hostComponentNE = hostComponentDE.nativeElement;

        componentDE = hostComponentDE.children[0];
        component = componentDE.componentInstance;
        componentNE = componentDE.nativeElement;

        fixture.detectChanges();
    });

    it('should display the component', () => {
        expect(hostComponentNE.querySelector('sb-card')).toEqual(jasmine.anything());
    });
});
Example #7
Source File: test-helpers.ts    From s-libs with MIT License 6 votes vote down vote up
export function findButton(
  fixture: ComponentFixture<any>,
  text: string,
): HTMLButtonElement {
  const found = fixture.debugElement.query(
    (candidate) =>
      candidate.nativeElement.nodeName === 'BUTTON' &&
      candidate.nativeElement.textContent.trim() === text,
  ) as DebugElement | null;
  if (found === null) {
    throw new Error('No button with text ' + text);
  } else {
    return found.nativeElement;
  }
}
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: table.spec.ts    From ngx-gantt with MIT License 6 votes vote down vote up
describe('NgxGanttTableComponent', () => {
    let component: TestGanttTableComponent;
    let fixture: ComponentFixture<TestGanttTableComponent>;

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

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

    it('should create ngx-gantt-table', () => {
        expect(component).toBeDefined();
        const ganttTable: DebugElement = fixture.debugElement.query(By.directive(GanttTableComponent));
        expect(ganttTable).toBeTruthy();
        expect(ganttTable.nativeElement).toBeTruthy();
    });
});
Example #10
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 #11
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 #12
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 #13
Source File: input-group.component.spec.ts    From alauda-ui with MIT License 5 votes vote down vote up
describe('InputGroupComponent', () => {
  let fixture: ComponentFixture<TestComponent>;
  let ins: TestComponent;
  let debugEl: DebugElement;
  let el: HTMLElement;
  let groupEl: HTMLElement;
  let innerWrapperEl: HTMLElement;
  let inputWrapperEl: HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [InputModule, IconModule],
      declarations: [TestComponent],
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    ins = fixture.componentInstance;
    debugEl = fixture.debugElement.query(By.css('aui-input-group'));
    el = debugEl.nativeElement;
    groupEl = el.querySelector('.aui-input-group');
    innerWrapperEl = groupEl.querySelector('.aui-input-group__inner-wrapper');
    inputWrapperEl = innerWrapperEl.querySelector(
      '.aui-input-group__input-wrapper',
    );
  });

  it('should render correct component construction', () => {
    expect(groupEl).not.toBeNull();
    expect(groupEl.className).toContain('aui-input-group--medium');
    expect(innerWrapperEl).not.toBeNull();
    expect(
      innerWrapperEl.querySelector('.aui-input-group__input-wrapper'),
    ).not.toBeNull();
  });

  it('should input-wrapper contain aui-input', () => {
    const inputEl = inputWrapperEl.querySelector('input');
    expect(inputEl).not.toBeNull();
    expect(inputEl.className).toContain('aui-input');
    expect(inputEl.className).toContain('aui-input--medium');
  });

  it('should render correct prefix & suffix', () => {
    expect(groupEl.className).toContain('hasPrefix');
    expect(groupEl.className).toContain('hasSuffix');
    expect(
      inputWrapperEl.querySelector('.aui-input-group__prefix'),
    ).not.toBeNull();
    expect(
      inputWrapperEl.querySelector('.aui-input-group__prefix .aui-icon'),
    ).not.toBeNull();
    expect(
      inputWrapperEl.querySelector('.aui-input-group__suffix'),
    ).not.toBeNull();
    expect(
      inputWrapperEl.querySelector('.aui-input-group__suffix .aui-icon'),
    ).not.toBeNull();
  });

  it('should render correct addon', () => {
    const addonEl = innerWrapperEl.querySelectorAll('.aui-input-group__addon');
    expect(addonEl.length).toBe(2);
    expect(addonEl[0]).not.toBeNull();
    expect(addonEl[0].className).toContain('aui-input-group__addon--before');
    expect(addonEl[1]).not.toBeNull();
    expect(addonEl[1].className).toContain('aui-input-group__addon--after');
  });

  it('should size option work correctly', () => {
    ins.size = ComponentSize.Mini;
    fixture.detectChanges();
    expect(groupEl.className).toContain('aui-input-group--mini');
    expect(el.querySelector('input').className).toContain('aui-input--mini');
  });

  it('should match snapshot', () => {
    expect(fixture).toMatchSnapshot();
  });
});
Example #14
Source File: button.spec.ts    From ASW-Form-Builder with MIT License 5 votes vote down vote up
describe('AswButton', () => {
    let component: AswButton;
    let fixture: ComponentFixture<AswButton>;
    // For query the DOM
    let debugElement: DebugElement;

    const control: any = {
        icon: 'touch_app',
        displayName: 'Button',
        controlType: 'button',
        name: 'button',
        tooltip: 'Click button',
        label: 'Button',
        type: 'button',
        color: 'primary',
        style: 'mat-raised-button',
        isRequired: false
    };

    const constants = {
        waringMessage: 'Are you sure you want to remove this field?'
    };

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [
                AswButton
            ],
            imports: [
                CommonModule,
                MatDialogModule,
                MatTooltipModule
            ],
            providers: [
                { provide: MAT_DIALOG_DATA, useValue: {} }
            ]
        }).compileComponents();
    });

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

    it('should display the button', () => {
        // setup input binding
        component.control = control;
        // detech SetupChanges
        fixture.detectChanges();
    });

    it('should open the AswConfirmDialog in a MatDialog', () => {
        const controlIndex = 1;
        spyOn(component.dialog, 'open').and.callThrough();
        component.deleteButtonDialog(control, controlIndex);
        expect(component.dialog.open).toHaveBeenCalledWith(AswConfirmDialog, {
            width: '350px',
            data: { name: control.name, message: constants.waringMessage }
        });
    });
});
Example #15
Source File: ngx-tippy-group.spec.ts    From ngx-tippy-wrapper with MIT License 5 votes vote down vote up
describe('Component: NgxTippyGroupComponent', () => {
  let injector: TestBed;
  let fixture: ComponentFixture<NgxTippyGroupComponent>;
  let component: NgxTippyGroupComponent;
  let debugEl: DebugElement;
  let platform: Object;

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

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

  it('should init tooltips only if platform browser', () => {
    spyOn(component, 'setTooltips');
    spyOn(component, 'initTippy');
    component.ngAfterViewInit();
    expect(component.setTooltips).toHaveBeenCalledTimes(0);
    expect(component.setTooltips).toHaveBeenCalledTimes(0);
  });
});
Example #16
Source File: results-hits.container.component.spec.ts    From geonetwork-ui with GNU General Public License v2.0 5 votes vote down vote up
describe('ResultsHitsContainerComponent', () => {
  let component: ResultsHitsContainerComponent
  let fixture: ComponentFixture<ResultsHitsContainerComponent>
  let de: DebugElement
  let items: DebugElement[]

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [
        ResultsHitsContainerComponent,
        MockResultsHitsNumberComponent,
      ],
      imports: [TranslateModule.forRoot()],
      providers: [
        {
          provide: SearchFacade,
          useValue: searchFacadeMock,
        },
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents()
  })

  beforeEach(() => {
    fixture = TestBed.createComponent(ResultsHitsContainerComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
    de = fixture.debugElement
    items = de.queryAll(By.directive(MockResultsHitsNumberComponent))
  })

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

  it('call ui component with params from State', () => {
    const uiComponent = items[0]
    expect(uiComponent).toBeTruthy()
    expect(uiComponent.componentInstance.loading).toBe(false)
    expect(uiComponent.componentInstance.hits).toBe(null)
  })
})
Example #17
Source File: side-nav.component.spec.ts    From dayz-server-manager with MIT License 5 votes vote down vote up
describe('SideNavComponent', () => {
    let fixture: ComponentFixture<TestHostComponent>;
    let hostComponent: TestHostComponent;
    let hostComponentDE: DebugElement;
    let hostComponentNE: Element;

    let component: SideNavComponent;
    let componentDE: DebugElement;
    let componentNE: Element;

    let navigationService: NavigationService;
    let userService: UserService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestHostComponent, SideNavComponent],
            imports: [NoopAnimationsModule],
            providers: [
                { provide: NavigationService, useValue: NavigationServiceStub },
                { provide: UserService, useValue: UserServiceStub },
            ],
            schemas: [NO_ERRORS_SCHEMA],
        }).compileComponents();

        fixture = TestBed.createComponent(TestHostComponent);
        hostComponent = fixture.componentInstance;
        hostComponentDE = fixture.debugElement;
        hostComponentNE = hostComponentDE.nativeElement;

        componentDE = hostComponentDE.children[0];
        component = componentDE.componentInstance;
        componentNE = componentDE.nativeElement;

        navigationService = TestBed.inject(NavigationService);
        userService = TestBed.inject(UserService);

        fixture.detectChanges();
    });

    it('should display the component', () => {
        expect(hostComponentNE.querySelector('sb-side-nav')).toEqual(jasmine.anything());
    });
});
Example #18
Source File: big-input.component.spec.ts    From enterprise-ng-2020-workshop with MIT License 5 votes vote down vote up
describe('BigInputComponent', () => {
  let fixture: ComponentFixture<HostComponent>;
  let component: HostComponent;
  let bigInputDebugElement: DebugElement;
  let inputNativeElement: HTMLInputElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [HostComponent],
      imports: [SharedModule, NoopAnimationsModule]
    });
    fixture = TestBed.createComponent(HostComponent);
    component = fixture.componentInstance;
    spyOn(component, 'onKeyEvent');
    bigInputDebugElement = fixture.debugElement.childNodes[0] as DebugElement;
    inputNativeElement = fixture.nativeElement.querySelector('input');
  });

  it('should have expected placeholder', () => {
    expect(bigInputDebugElement.attributes['placeholder']).toContain(
      'going to do'
    );
  });

  it('should have updatable value', () => {
    component.newValue = 'abcde';
    fixture.detectChanges();
    expect(inputNativeElement.value).toBe(component.newValue);
  });

  it('should respond to keyup event', () => {
    const expectedEventData = 'Key UP';
    bigInputDebugElement.triggerEventHandler('keyup', expectedEventData);

    expect(component.onKeyEvent).toHaveBeenCalledTimes(1);
    expect(component.onKeyEvent).toHaveBeenCalledWith(expectedEventData);
  });

  it('should respond to keyup.enter event', () => {
    const expectedEventData = 'Enter UP';
    bigInputDebugElement.triggerEventHandler('keyup.enter', expectedEventData);

    expect(component.onKeyEvent).toHaveBeenCalledTimes(1);
    expect(component.onKeyEvent).toHaveBeenCalledWith(expectedEventData);
  });

  it('should respond to escape event', () => {
    const expectedEventData = 'Escape UP';
    bigInputDebugElement.triggerEventHandler('keyup.escape', expectedEventData);

    expect(component.onKeyEvent).toHaveBeenCalledTimes(1);
    expect(component.onKeyEvent).toHaveBeenCalledWith(expectedEventData);
  });

  it('should respond to focus and blur', () => {
    expect(bigInputDebugElement.componentInstance.hasFocus).toBe(
      false,
      'before focus'
    );

    inputNativeElement.dispatchEvent(new Event('focus'));
    expect(bigInputDebugElement.componentInstance.hasFocus).toBe(
      true,
      'after focus'
    );

    inputNativeElement.dispatchEvent(new Event('blur'));
    expect(bigInputDebugElement.componentInstance.hasFocus).toBe(
      false,
      'after blur'
    );
  });
});
Example #19
Source File: bar.drag.spec.ts    From ngx-gantt with MIT License 5 votes vote down vote up
describe('bar-drag', () => {
    let fixture: ComponentFixture<TestGanttBarComponent>;
    let ganttComponentInstance: TestGanttBarComponent;
    let ganttDebugElement: DebugElement;

    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [CommonModule, NgxGanttModule],
            declarations: [TestGanttBarComponent]
        }).compileComponents();
        fixture = TestBed.createComponent(TestGanttBarComponent);
        ganttDebugElement = fixture.debugElement.query(By.directive(NgxGanttComponent));
        ganttComponentInstance = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should active when mouse enter bar', () => {
        const barElement = fixture.debugElement.query(By.directive(NgxGanttBarComponent)).nativeElement;
        dispatchMouseEvent(barElement, 'mouseenter');
        expect(barElement.classList).toContain(activeClass);
        dispatchMouseEvent(barElement, 'mouseleave');
        expect(barElement.classList).not.toContain(activeClass);
    });

    it('should bar drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[0];
        dragEvent(fixture, bar.nativeElement);
        expect(bar.componentInstance.item.start.getUnixTime()).toEqual(new GanttDate('2020-04-21 00:00:00').getUnixTime());
        expect(bar.componentInstance.item.end.getUnixTime()).toEqual(new GanttDate('2020-06-26 23:59:59').getUnixTime());
    });

    it('should first bar handle drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[1];
        const firstHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[0].nativeElement;
        dragEvent(fixture, firstHandleElement, bar.nativeElement);
        expect(bar.componentInstance.item.start.getUnixTime()).toEqual(new GanttDate('2020-05-14 00:00:00').getUnixTime());
    });

    it('should last bar handles drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[1];
        const lastHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[1].nativeElement;
        dragEvent(fixture, lastHandleElement, bar.nativeElement);
        expect(bar.componentInstance.item.end.getUnixTime()).toEqual(new GanttDate('2020-07-15 23:59:59').getUnixTime());
    });

    it('should first bar link handle drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[2];
        const firstHandleElement = bar.queryAll(By.css('.link-handles .handle'))[0].nativeElement;
        linkDragEvent(fixture, firstHandleElement);
    });

    it('should last bar link handles drag', () => {
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[2];
        const lastHandleElement = bar.queryAll(By.css('.link-handles .handle'))[1].nativeElement;
        linkDragEvent(fixture, lastHandleElement);
    });

    it('should not run change detection when the `mousedown` is dispatched on the handle', () => {
        const appRef = TestBed.inject(ApplicationRef);
        spyOn(appRef, 'tick');
        const bar = fixture.debugElement.queryAll(By.directive(NgxGanttBarComponent))[0];
        const firstHandleElement = bar.queryAll(By.css('.drag-handles .handle'))[0].nativeElement;
        const event = new Event('mousedown');
        spyOn(event, 'stopPropagation').and.callThrough();
        firstHandleElement.dispatchEvent(event);
        expect(appRef.tick).not.toHaveBeenCalled();
        expect(event.stopPropagation).toHaveBeenCalled();
    });
});
Example #20
Source File: login.component.spec.ts    From ng-conf-2020-workshop with MIT License 4 votes vote down vote up
describe('LoginComponent', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;
  const extAuthSpy = jasmine.createSpyObj('ExternalAuthService', ['login', 'hasProvider']);
  const authSpy = jasmine.createSpyObj('AuthenticationService', ['login']);
  const userServSpy = jasmine.createSpyObj('UserService', ['setCurrentUser']);

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, RouterTestingModule, NoopAnimationsModule,
        IgxInputGroupModule, IgxButtonModule, IgxIconModule, IgxRippleModule ],
      declarations: [ LoginComponent ],
      providers: [
        { provide: ExternalAuthService, useValue: extAuthSpy },
        { provide: AuthenticationService, useValue: authSpy },
        { provide: UserService, useValue: userServSpy }
      ]
    })
    .compileComponents();
  }));

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

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

  it('should submit login data',  async () => {
    const router: Router = TestBed.inject(Router);
    spyOn(router, 'navigate');
    expect(component.loginForm.valid).toBeFalsy();
    component.loginForm.controls[MAIL_GROUP_NAME].setValue('[email protected]');
    expect(component.loginForm.valid).toBeFalsy();
    component.loginForm.controls[PASSWORD_GROUP_NAME].setValue('123456');
    expect(component.loginForm.valid).toBeTruthy();
    spyOn(component.loggedIn, 'emit');
    authSpy.login.and.returnValue(Promise.resolve({
      error: null,
      user: { name: 'TEST' }
    }));
    await component.tryLogin();
    expect(authSpy.login).toHaveBeenCalledTimes(1);
    expect(authSpy.login).toHaveBeenCalledWith({
      email: '[email protected]',
      password: '123456'
    });
    expect(userServSpy.setCurrentUser).toHaveBeenCalledWith({name: 'TEST'});
    expect(component.loggedIn.emit).toHaveBeenCalled();
    expect(router.navigate).toHaveBeenCalledWith(['/profile']);

    authSpy.login.and.returnValue(Promise.resolve({
      error: 'Err'
    }));
    spyOn(window, 'alert');
    await component.tryLogin();
    expect(window.alert).toHaveBeenCalledWith('Err');
  });

  it('should enable external auth buttons when configured', () => {
    let activeProvider = ExternalAuthProvider.Facebook;
    const has = (provider: ExternalAuthProvider) => provider ? provider === activeProvider : true;
    (extAuthSpy.hasProvider as jasmine.Spy).and.callFake(has);
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('button.facebook'))).toEqual(jasmine.any(DebugElement));
    expect(fixture.debugElement.query(By.css('button.google'))).toBeNull();
    expect(fixture.debugElement.query(By.css('button.microsoft'))).toBeNull();
    activeProvider = ExternalAuthProvider.Google;
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('button.facebook'))).toBeNull();
    expect(fixture.debugElement.query(By.css('button.google'))).toEqual(jasmine.any(DebugElement));
    expect(fixture.debugElement.query(By.css('button.microsoft'))).toBeNull();
  });

  it('should call correct external auth login per button', () => {
    (extAuthSpy.hasProvider as jasmine.Spy).and.returnValue(true);
    fixture.detectChanges();
    spyOn(component.loggedIn, 'emit');
    fixture.debugElement.query(By.css('button.facebook')).nativeElement.click();
    expect(extAuthSpy.login).toHaveBeenCalledWith(ExternalAuthProvider.Facebook);
    expect(component.loggedIn.emit).toHaveBeenCalled();

    fixture.debugElement.query(By.css('button.google')).nativeElement.click();
    expect(extAuthSpy.login).toHaveBeenCalledWith(ExternalAuthProvider.Google);

    fixture.debugElement.query(By.css('button.microsoft')).nativeElement.click();
    expect(extAuthSpy.login).toHaveBeenCalledWith(ExternalAuthProvider.Microsoft);
  });

  it('should emit viewChange on "create account" click', () => {
    spyOn(fixture.componentInstance.viewChange, 'emit');
    fixture.debugElement.query(By.css('#register')).nativeElement.click();
    expect(fixture.componentInstance.viewChange.emit).toHaveBeenCalled();
  });
});
Example #21
Source File: accordion-item.component.spec.ts    From canopy with Apache License 2.0 4 votes vote down vote up
describe('LgAccordionItemComponent', () => {
  let component: LgAccordionItemComponent;
  let fixture: ComponentFixture<TestAccordionWrapperItemComponent>;
  let triggerElement: DebugElement;
  let selectionDispatcher: UniqueSelectionDispatcher;
  let accordionMock: any;

  beforeEach(waitForAsync(() => {
    accordionMock = { id: 'lgAccordion123' };

    TestBed.configureTestingModule({
      declarations: [
        TestAccordionWrapperItemComponent,
        LgAccordionItemComponent,
        LgAccordionPanelHeadingComponent,
        LgAccordionItemContentDirective,
        MockComponents(LgHeadingComponent, LgIconComponent),
      ],
      providers: [ { provide: LG_ACCORDION, useFactory: () => accordionMock } ],
    }).compileComponents();
  }));

  beforeEach(() => {
    selectionDispatcher = TestBed.inject(UniqueSelectionDispatcher);
    fixture = TestBed.createComponent(TestAccordionWrapperItemComponent);
    component = fixture.debugElement.children[0].componentInstance;
    fixture.detectChanges();

    triggerElement = fixture.debugElement.query(By.css('.lg-accordion__heading-toggle'));
  });

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

  it('should render panel content', () => {
    expect(fixture.debugElement.query(By.css('.default-content'))).toBeDefined();
  });

  describe('when panel content is lazy loaded', () => {
    describe('and panel is not active', () => {
      it('should not show content', () => {
        expect(fixture.debugElement.query(By.css('.lazy-content'))).toBeNull();
      });
    });

    describe('and panel is active', () => {
      beforeEach(() => {
        fixture.debugElement.componentInstance.lazyIsOpen = true;
        fixture.detectChanges();
      });

      it('should show content', () => {
        expect(fixture.debugElement.query(By.css('.lazy-content'))).toBeDefined();
      });
    });
  });

  describe('clicking on the child component trigger', () => {
    let openedSpy: jasmine.Spy;
    let closedSpy: jasmine.Spy;
    let selectionDispatcherSpy: jasmine.Spy;

    beforeEach(() => {
      openedSpy = spyOn(component.opened, 'emit');
      closedSpy = spyOn(component.closed, 'emit');
      selectionDispatcherSpy = spyOn(selectionDispatcher, 'notify');
    });

    it('should update \'isActive\'', () => {
      triggerElement.nativeElement.click();

      expect(component.isActive).toBe(true);

      triggerElement.nativeElement.click();

      expect(component.isActive).toBe(false);
    });

    it('should emit events', () => {
      triggerElement.nativeElement.click();

      expect(openedSpy).toHaveBeenCalled();
      expect(selectionDispatcherSpy).toHaveBeenCalledTimes(1);

      triggerElement.nativeElement.click();

      expect(closedSpy).toHaveBeenCalled();
      expect(selectionDispatcherSpy).toHaveBeenCalledTimes(1);
    });
  });

  it('should toggle the `active` class on the panel', () => {
    const panelElement = fixture.debugElement.query(By.css('.lg-accordion__panel'));

    expect(
      panelElement.nativeElement.classList.contains('lg-accordion__panel--active'),
    ).toBe(false);

    triggerElement.nativeElement.click();
    fixture.detectChanges();

    expect(
      panelElement.nativeElement.classList.contains('lg-accordion__panel--active'),
    ).toBe(true);
  });

  describe('when updating isActive input', () => {
    it('should set heading active', () => {
      fixture.debugElement.componentInstance.isActive = true;
      fixture.detectChanges();

      expect(component.isActive).toBeTruthy();
      expect(component.accordionPanelHeading.isActive).toBeTruthy();
    });

    it('should emit opened event', () => {
      component.opened.pipe(take(1)).subscribe(ev => {
        expect(ev).toBeUndefined();
      });

      fixture.debugElement.componentInstance.isActive = true;
      fixture.detectChanges();
    });

    it('should emit closed event', () => {
      component.closed.pipe(take(1)).subscribe(ev => {
        expect(ev).toBeUndefined();
      });

      fixture.debugElement.componentInstance.isActive = false;
      fixture.detectChanges();
    });
  });

  describe('when notified of sibling accordion item activated', () => {
    const someOtherId = 'some-other-id';
    let closedSpy: jasmine.Spy;

    beforeEach(() => {
      fixture.debugElement.componentInstance.isActive = true;
      fixture.detectChanges();
      closedSpy = spyOn(component.closed, 'emit');
    });

    describe('and accordion is in multi mode', () => {
      beforeEach(() => {
        accordionMock.multi = true;
      });

      it('does nothing', () => {
        selectionDispatcher.notify(someOtherId, accordionMock.id);

        expect(closedSpy).not.toHaveBeenCalled();
      });
    });

    describe('and accordion is in single item active mode', () => {
      beforeEach(() => {
        accordionMock.multi = false;
      });

      it('deactivates active panel', () => {
        selectionDispatcher.notify(someOtherId, accordionMock.id);

        expect(closedSpy).toHaveBeenCalled();
        expect(component.isActive).toBeFalsy();
        expect(component.accordionPanelHeading.isActive).toBeFalsy();
      });
    });
  });
});