Angular的fixture的debugElement为NULL。
创始人
2024-10-24 03:00:58
0

在Angular中,debugElement为NULL通常是因为fixture还没有完成初始化。解决这个问题的方法是使用async/await或者使用fixture的detectChanges方法来确保fixture的初始化完成。

下面是一个使用async/await的示例代码:

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('should create', async () => {
    fixture.detectChanges();
    await fixture.whenStable(); // 等待fixture初始化完成
    expect(component).toBeTruthy();
  });
});

在上述代码中,我们使用了async/await来等待fixture初始化完成。在测试方法中,我们首先调用fixture.detectChanges()来触发组件的变化检测,然后使用fixture.whenStable()来等待fixture初始化完成。

另一种解决方法是使用fixture的detectChanges方法:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    fixture.detectChanges();
    fixture.whenStable().then(() => { // 使用whenStable方法来等待fixture初始化完成
      expect(component).toBeTruthy();
    });
  });
});

在上述代码中,我们仍然使用fixture.detectChanges()来触发组件的变化检测,然后使用fixture.whenStable().then()来等待fixture初始化完成,并在回调函数中进行断言。

无论使用哪种方法,都可以确保fixture初始化完成后再访问debugElement。

相关内容

热门资讯

有挂秘籍开挂!全民内蒙古辅助,... 有挂秘籍开挂!全民内蒙古辅助,789大菠萝可以控制吗(推荐十款开挂辅助软件)您好:789大菠萝可以控...
确实有挂开挂!川滇互娱app辅... >>您好:川滇互娱app辅助确实是有挂的,很多玩家在这款川滇互娱app辅助游戏中打牌都会发现很多用户...
有挂规律开挂!微信小程序辅助器... 微信小程序辅助器出租 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理由:...
有挂教程开挂!赣州冲关辅助,情... 有挂教程开挂!赣州冲关辅助,情怀宜春辅助(科技新动态开挂辅助软件)您好:情怀宜春辅助这款游戏可以开挂...
有挂教程开挂!关春天开挂,德普... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
存在有挂开挂!小程序牵手跑得快... 存在有挂开挂!小程序牵手跑得快辅助器,中至赣州黑科技辅助软件(如何分辨真伪开挂辅助下载)>>您好:软...
有挂技巧辅助!微乐老友广东辅助... 有挂技巧辅助!微乐老友广东辅助器,乐平讨赏挂(透视最新开挂辅助插件)微乐老友广东辅助器ai黑科技系统...
有挂讲解开挂!填大坑辅助器,老... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
有挂分析辅助!授权二厅辅助,中... 有挂分析辅助!授权二厅辅助,中至赣州黑科技辅助软件视频(玩家必备科普开挂辅助软件)>>您好:软件加1...
有挂技巧辅助!腾威互娱 辅助工... 腾威互娱 辅助工具是一款专注玩家量身打造的游戏记牌类型软件,在腾威互娱 辅助工具这款游戏中我们可以记...