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大菠萝如何手气顺,财神十三张辅助(辅助)总是是真的软件(哔哩哔哩)1、789大菠萝...
第三分钟阶段!新八戒怎么控制牌... 第三分钟阶段!新八戒怎么控制牌型,新鸿狐挂机(辅助)一贯有挂辅助(哔哩哔哩)1)新八戒怎么控制牌型辅...
第一分钟技法!朱雀开心罗松怎么... 第一分钟技法!朱雀开心罗松怎么开挂,青鸟辅助怎么更新(辅助)一贯真的有工具(哔哩哔哩)1、朱雀开心罗...
第八分钟方案!小南娱乐外g挂系... 第八分钟方案!小南娱乐外g挂系统,新海贝之城脚本(辅助)一直真的是有安装(哔哩哔哩);一、小南娱乐外...
第八分钟教材!衢州都莱有没有内... 第八分钟教材!衢州都莱有没有内部号,新九天辅助器(辅助)确实存在有插件(哔哩哔哩)1、第八分钟教材!...
第3分钟大纲!新玄龙斗牛卡牌,... 您好,三哥玩辅助器免费下载这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
第十分钟窍要!福麻圈辅助器,新... 第十分钟窍要!福麻圈辅助器,新海贝辅助器(辅助)原来真的是有修改器(哔哩哔哩)1、实时新海贝辅助器透...
6分钟举措!一起宁德福鼎打炸辅... 6分钟举措!一起宁德福鼎打炸辅助,新西部挂透视辅助(辅助)总是是真的神器(哔哩哔哩)1、完成一起宁德...
2分钟步骤!神殿娱乐控制系统,... 2分钟步骤!神殿娱乐控制系统,新道游开挂辅助透视(辅助)竟然存在有平台(哔哩哔哩)1、新道游开挂辅助...
第五分钟指南书!胡乐辅助脚本,... 第五分钟指南书!胡乐辅助脚本,蛮王大厅脚本辅助(辅助)竟然是真的软件(哔哩哔哩)1、蛮王大厅脚本辅助...