簡體   English   中英

Angular 4 Fixture 組件在 Jasmine 測試期間保留在 DOM 中

[英]Angular 4 fixture component persists in DOM during Jasmine tests

在真實瀏覽器中運行 Jasmine 時,我注意到TestBed固定組件在 DOM 中沒有被銷毀,並且在測試結束后仍然存在:

在此處輸入圖片說明

這是一個經過測試的組件:

@Component({
  selector: 'test-app',
  template: `<div>Test</div>`,
})
class 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();
  });

為什么Test組件實例沒有從 DOM 中刪除,這應該如何解決?

為什么要在 DOM 中添加夾具組件? 它們可以像 AngularJS 中的$rootElement一樣從 DOM 中分離出來嗎?

我認為 Angular 不會自動刪除它來幫助您獲取有關測試執行的更多詳細信息。 要刪除它,您只需使用 afterEach:

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

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

更簡潔的解決方案:

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

其中elementfixture.debugElement.nativeElement

請看以下問題:

1)首先你打電話

fixture.destroy();

afterEach 中,所以它在部分之后被調用。 即在部分夾具仍然沒有被破壞

2) 你通過什么代碼檢測到元素仍然存在於 DOM 中? 從另一個角度來看:為什么那個元素應該被 jasmine/browser 刪除(什么原因應該讓 jasmine/browser )? 我可以建議以下用例:

2.1) 一個組件在另一個組件中使用,應該通過一些更改創建/銷毀。 ngIfngSwitchCase

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

或者

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

2.2) 路由已更改(但它不是單元測試 AFAIK 的主題)

3) 當前代碼只接收一次對 DOM 元素的引用。 應該是這樣的:

beforeEach(() => {
    ...
    element = ...
});

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

4) 如果您試圖查找諸如ngOnDestroy()已定義但未使用實現 OnDestroy 之類的錯誤,那么它更像是npm run lint而非單元測試的主題(請查看tslint 中的use-life-cycle-interface 。 json )。 運行npm run lint 后,您將看到:

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

不僅對於單元測試而且對於 tslint 都沒有錯誤是一個很好的做法。

我還經歷過測試用例對DOM所做的更改,例如:

let password = fixture.debugElement.query(By.css('input[id=password]')).nativeElement
    password.value = 'somePassword';

在其他測試中保持不變。 我能夠通過使用以下afterEach方法解決此問題:

afterEach(() => {
    TestBed.resetTestingModule();
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM