Home > database >  How can I cover unit test case for eventEmitter object exists in abstract class (jasmine / Angular8)
How can I cover unit test case for eventEmitter object exists in abstract class (jasmine / Angular8)

Time:06-17

I am trying to cover the unit test case for the following scenario but not working

AbstractClass.ts

@Directive
export abstract class AbstractComponent<search = string> {
  @Output()
  public search: EventEmitter<string> = new EventEmitter();
}

MyComponent.component.ts

@Component({
   selector: my-component,
   templateUrl: './my.component.html',
   styleUrls: ['./my.component.scss'],
})
export class MyComponent extends AbstractComponent implements OnInit {
 
 public ngOnInit(): void {
    this.search.subscribe((text: string) => { //This subscribe not covering in unit test case
        // do something
    });
 }

}

spec.ts

beforeEach(async () => {
    await TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [VzUiNavigationModule, RouterTestingModule.withRoutes([]), HttpClientTestingModule],
        providers: [
            Store,
            MyService
        ],
    }).compileComponents();
});
it('should validate ngOnInit', () => {
    spyOn(component.search, 'next').and.returnValue('ABC');
    
    spyOn(component.onSearch, 'emit').and.returnValue(of('ABC'));
    spyOn(component.onSearch, 'subscribe').and.returnValue('ABC');
    component.ngOnInit();
    fixture.detectChanges(true);
    expect(component).toBeTruthy();
});

CodePudding user response:

Try this:

it('should validate ngOnInit', () => {
  component.ngOnInit();
  component.search.emit('abc');
  // what's inside of the sbuscribe should be traversed now.
});
  • Related