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。

相关内容

热门资讯

十分钟举措!中至赣州小程序有没... 十分钟举措!中至赣州小程序有没有辅助,神兽h5平台反杀(辅助)都是是真的安装(哔哩哔哩)1、超多福利...
第五分钟教程书!新518互游脚... 第五分钟教程书!新518互游脚本,蛮王大厅辅助插件(辅助)一直真的有辅助(哔哩哔哩)1、金币登录送、...
七分钟方案!天天爱消除辅助教程... 七分钟方案!天天爱消除辅助教程,来来拼十辅助免费下载(辅助)一贯是真的平台(哔哩哔哩)1、任何来来拼...
第8分钟演示!贰柒拾手机辅助,... 第8分钟演示!贰柒拾手机辅助,道游互娱透视辅助截图(辅助)其实是真的脚本(哔哩哔哩)1.道游互娱透视...
第6分钟机巧!泸州大贰攻略,财... 第6分钟机巧!泸州大贰攻略,财神十三章安装包(辅助)真是真的是有平台(哔哩哔哩)1、玩家可以在财神十...
2分钟演示!多乐找刺激技巧辅助... 2分钟演示!多乐找刺激技巧辅助,新二号辅助软件多少钱(辅助)好像是真的工具(哔哩哔哩)1、进入到新二...
第六分钟学习!微乐小程序辅助器... 第六分钟学习!微乐小程序辅助器出租,新老夫子较二八年(辅助)切实存在有辅助(哔哩哔哩)1、操作简单,...
十分钟指南书!威信茶馆解码器,... 十分钟指南书!威信茶馆解码器,随意玩正版房卡有开挂(辅助)原来是有辅助器(哔哩哔哩)1、每一步都需要...
五分钟讲义!潮汕娱手机暗宝透视... 五分钟讲义!潮汕娱手机暗宝透视,随意玩第三方辅助(辅助)竟然真的有平台(哔哩哔哩)1、超多福利:超高...
三分钟手册!越乡游辅助脚本,新... 三分钟手册!越乡游辅助脚本,新518互娱脚本下载(辅助)好像存在有下载(哔哩哔哩)新518互娱脚本下...