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。

相关内容

热门资讯

热门推荐!微信小程序多功能辅助... 热门推荐!微信小程序多功能辅助,盛世辅助器,详细app(有挂神器)1、实时微信小程序多功能辅助透视辅...
最新技巧!黑科技微乐小程序辅助... 最新技巧!黑科技微乐小程序辅助器免费,随意玩工具箱辅助器,详细教程(真是有挂)1、点击下载安装,黑科...
盘点十款!乐乐围棋入门辅助,小... 盘点十款!乐乐围棋入门辅助,小程序游戏赴沪期,详细app(有挂教学)1、首先打开小程序游戏赴沪期辅助...
实操分享!新超凡手游辅助,雀友... 实操分享!新超凡手游辅助,雀友会广东潮汕麻雀万能辅助器,详细挂(有挂教程)1、全新机制【雀友会广东潮...
一起来探讨!纳祥游戏脚本,微信... 一起来探讨!纳祥游戏脚本,微信小程序辅助工具,详细攻略(有挂解惑)1、这是跨平台的微信小程序辅助工具...
一分钟揭秘!新八戒辅助,挂是真... 一分钟揭秘!新八戒辅助,挂是真的假的,详细器(确实有挂)1、全新机制【挂是真的假的ai辅助工具激活码...
最新通报!微信小程序微乐房间怎... 最新通报!微信小程序微乐房间怎么开挂,打哈儿床将辅助最新,详细软件(有挂技巧)1、全新机制【微信小程...
玩家实测!欢乐达人暗堡破解,赣... 您好,欢乐达人暗堡破解这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩...
一分钟揭秘!情怀手机麻将辅助器... 一分钟揭秘!情怀手机麻将辅助器,功夫川麻辅助,详细工具(详细教程)1、金币登录送、破产送、升级送、活...
今日科普!微信广东雀神挂件辅助... 今日科普!微信广东雀神挂件辅助,对战互娱辅助系统,详细神器(有挂规律);1、下载好微信广东雀神挂件辅...