Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
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?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Jasmine nor Angular will ever remove it automatically, maybe to help you to get more details about your test execution.

To remove it you simply use afterEach(...), like:

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

afterEach(() => {
  document.body.removeChild(element);
});

For none Angular users:

afterEach(() => {
    document.body.innerHTML = '';
});

Above clears all default <script> tags, but that does not matter (because they did already run, and Karma does never refresh the browser, at least not till all tests finish).

over 4 years ago · Santiago Trujillo Relatório

0

A more concise solution:

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

Where element is fixture.debugElement.nativeElement

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda