简体   繁体   中英

How to test an angular component that uses primeng component

I'll try to keep the code as minimal as possible. I've just started watching lectures on Pluralsight on Unit testing. I've a TimeselectorComponent , on click it should open an overlay with some hard coded text. That overlay is actually p-overlayPanel from primeng . I just want to write a unit test using Jasmine and Karma that when I click on TimeselectorComponent then the overlay should come up. Here's the code:

timeselector.component.html

<div (click)="op.toggle($event)">
    Click to see the text
</div>

<div class="timeselector">
  <p-overlayPanel #op>
    <div>
      <p>Hello world!</p>
    </div>
   </p-overlayPanel>
</div>

Here's my spec file:

import { TestBed, ComponentFixture, async } from "@angular/core/testing"
import { TimeselectorComponent } from './timeselector.component'
import { Component, Input } from '@angular/core';
import { FormsModule } from '@angular/forms';
...

describe('TimeselectorComponent', () => {
    let fixture: ComponentFixture<TimeselectorComponent>;

    @Component({
        selector: 'p-overlayPanel',
        template: '<div></div>'
    })
    class FakePOverlayPanel {
    }

    beforeEach(async(()=>{
        TestBed.configureTestingModule({
            imports: [
                FormsModule
            ],
            providers: [

            ],
            declarations: [
                TimeselectorComponent,
                FakePOverlayPanel
            ]
        });
        fixture = TestBed.createComponent(TimeselectorComponent);

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

    it('should apply filters across dashboards', () => {
        // assert

        // expect
    })
})

Please correct me. Is it even testable? Please help me.

  1. In your TestBed.configureTestingModule you have to import:
BrowserAnimationsModule,
OverlayPanelModule,
  1. In your test:
let debugEl: DebugElement = fixture.debugElement;
debugEl.nativeElement.click();

fixture.detectChanges();
  
let overlayPanel = debugEl.query(By.directive(OverlayPanel));
expect(overlayPanel).toBeTruthy();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM