Angular 4 fixture component persists in DOM during Jasmine tests Angular 4 fixture component persists in DOM during Jasmine tests typescript typescript

Angular 4 fixture component persists in DOM during Jasmine tests


I think Angular does not remove it automatically to help you to get more details about your test execution. To remove it you simply use afterEach:

beforeEach(() => {  fixture = TestBed.createComponent(MyComponent);  comp = fixture.componentInstance;  debugElement = fixture.debugElement;  element = debugElement.nativeElement;}); afterEach(() => {  document.body.removeChild(element);});


A more concise solution:

afterEach(() => {  element.remove()});

Where element is fixture.debugElement.nativeElement


Please take a look at the following issues:

1) first of all you are calling

fixture.destroy();

in afterEach, so it's called after it section. I.e. in it section fixture is still not destroyed

2) by what code do you detect that element is still present in DOM? From another point of view: why that element should be removed by jasmine/browser (what reason should make jasmine/browser)? I could suggest the following usecases:

2.1) one component is used in another one and should be created/destroyed by some change. I.e. ngIf or ngSwitchCase:

<parent-component>    <child-component *ngIf="someChangeInComponent1"></child-component></parent-component>

or

<parent-component [ngSwitch]="type">    <child-component *ngSwitchCase="'something'"></child-component></parent-component>

2.2) routing is changed (but it's not a subject for unit-tests AFAIK)

3) current code receives the reference to DOM element only once. Should be something like:

beforeEach(() => {    ...    element = ...});it('...', () => {    ...    fixture.detectChanges();    element = ... // try to get element again <--------------------- here})

4) if you are trying to find errors like ngOnDestroy() is defined but implements OnDestroy is not used then it's more a subject for npm run lint than for unit tests (please take a look at use-life-cycle-interface in tslint.json). After running npm run lint you'll just see:

Implement lifecycle hook interface OnDestroy for method ngOnDestroy in class ...

It's a good practice to have no errors not only for unit test but for tslint too.