Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 fixture component persists in DOM during Jasmine tests

When running Jasmine in real browser I noticed that TestBed fixture component isn't destroyed in DOM and persists after tests have ended:

enter image description here

Here's a tested component:

@Component({   selector: 'test-app',   template: `<div>Test</div>`, }) class Test {} 

And a test (plunk).

  let component;   let fixture;   let element;    beforeAll(() => {     TestBed.resetTestEnvironment();      TestBed.initTestEnvironment(       BrowserDynamicTestingModule,       platformBrowserDynamicTesting()     );   });    beforeEach(() => {     TestBed.configureTestingModule({       declarations: [Test],     })     .compileComponents();      fixture = TestBed.createComponent(Test);     component = fixture.componentInstance;     element = fixture.debugElement.query(By.css('div')).nativeElement;      fixture.detectChanges();   });    afterEach(() => {     fixture.destroy();   });    it('should compile Test', () => {     expect(element).toBeTruthy();   }); 

Why Test component instance isn't removed from DOM and how this should be fixed?

Why are fixture components added to DOM at all? Can they be detached from DOM like $rootElement in AngularJS?

like image 530
Estus Flask Avatar asked Apr 26 '17 22:04

Estus Flask


People also ask

What is fixture in Jasmine?

Jasmine Fixtures is an add-on for the behavior-driven development framework, Jasmine. If you're using Jasmine to test the JavaScript in your Ruby projects and you want to test your DOM and bindings, you can use Jasmine Fixtures.

What does detectChanges do in Angular Jasmine tests?

detectChanges(). Delayed change detection is intentional and useful. It gives the tester an opportunity to inspect and change the state of the component before Angular initiates data binding and calls lifecycle hooks.

What is TestBed in Jasmine?

TestBed is a mock environment to run Angular2 component tests without the browser.

What is fixture debugElement?

DebugElement is an Angular class that contains all kinds of references and methods relevant to investigate an element as well as component fixture.debugElement.query(By.css('#shan'))


1 Answers

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); }); 
like image 133
Julia Passynkova Avatar answered Sep 29 '22 20:09

Julia Passynkova