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。

相关内容

热门资讯

我来教教大家!陕麻圈延安划水辅... 我来教教大家!陕麻圈延安划水辅助,wepoker插件功能辅助器,扑克教程(有挂实锤)是一款可以让一直...
玩家必看科普!互游辅助,丽水都... 玩家必看科普!互游辅助,丽水都莱辅助软件(好像有挂)1、丽水都莱辅助软件透视辅助软件激活码多个强度级...
分享个大家!小程序牵手跑得有辅... 分享个大家!小程序牵手跑得有辅助器,微乐四川麻将辅助器(果然是真的有挂)1、超多福利:超高返利,海量...
必看攻略!家乡大贰小程序靠谱吗... 必看攻略!家乡大贰小程序靠谱吗,wpk俱乐部怎么作弊,玩家教你(有挂教程)是一款可以让一直输的玩家,...
分享认知!牵手辅助神器下载,微... 分享认知!牵手辅助神器下载,微乐降序自建房辅助app(都是真的是有挂)暗藏猫腻,小编详细说明微乐降序...
2024教程!丽水都莱大菠萝脚... 2024教程!丽水都莱大菠萝脚本辅助,wepoker破解是真的还是假的,新2025教程(揭秘有挂);...
一分钟秒懂!798大菠萝辅助,... 一分钟秒懂!798大菠萝辅助,茶馆游戏辅助(总是是真的有挂)1、金币登录送、破产送、升级送、活动送。...
科技分享!边锋干瞪眼ios辅助... 【福星临门,好运相随】;科技分享!边锋干瞪眼ios辅助微信,佛手大菠萝辅助,必赢方法(新版有挂);暗...
实操分享!微信小程序开发辅助,... 实操分享!微信小程序开发辅助,潮友会辅助(切实真的是有挂)1、金币登录送、破产送、升级送、活动送。详...
发现玩家!途游辅助器软件,we... 发现玩家!途游辅助器软件,wepoker怎么拿到好牌,教你攻略(有挂教程)是一款可以让一直输的玩家,...