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这款游戏可以开挂的,确实是有挂的,需要了解加去威信【13670430...
科技通报!微乐小程序黑科技(透... 科技通报!微乐小程序黑科技(透视器),微乐踢坑原来存在有透视挂技巧1.微乐小程序黑科技 选牌创建新账...
玩家攻略推荐!微乐自建房辅助软... 玩家攻略推荐!微乐自建房辅助软件功能(透视挂),微乐河池麻将本来是有透视挂app1、首先打开微乐自建...
一分钟了解!微乐小程序怎么挂脚... 一分钟了解!微乐小程序怎么挂脚本(作弊器),微乐鞍山麻将一直存在有透视挂脚本1、微乐小程序怎么挂脚本...
推荐攻略!微信小程序微乐陕西挖... 推荐攻略!微信小程序微乐陕西挖坑(辅助),微乐邵阳麻将本来有透视挂工具1、进入游戏-大厅左侧-新手福...
一分钟揭秘!万能透视辅助器免费... 一分钟揭秘!万能透视辅助器免费版(辅助器),微乐新余50k有本来存在有透视挂教程1、金币登录送、破产...
一分钟带你了解辅助器!河马互娱... 一分钟带你了解辅助器!河马互娱ai智能辅助器app,河马互娱透视开挂阶段(原来发现有挂)1、河马互娱...
实测发现辅助器!红桃k大厅ai... 实测发现辅助器!红桃k大厅ai智能辅助器攻略,红桃k大厅真的有挂机巧(真是有挂技术)1.红桃k大厅 ...
最终透视挂!悠悠一区ai智能透... 最终透视挂!悠悠一区ai智能透视挂方法,悠悠一区有挂吗总结(果然真的有挂)1、超多福利:超高返利,海...
玩家攻略推荐透视!可乐大厅ai... 玩家攻略推荐透视!可乐大厅ai智能透视插件,可乐大厅可以装挂吗方式(其实发现有挂)可乐大厅破解侠是真...