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。

相关内容

热门资讯

开挂辅助下载"pok... 开挂辅助下载"pokemmo辅助器"开挂(透视)辅助下载(竟然有挂);无需打开直接搜索加薇13670...
开挂辅助平台"德州局... 开挂辅助平台"德州局怎么透视"开挂(透视)辅助脚本(有挂头条)您好:德州局怎么透视这款游戏可以开挂,...
开挂辅助安装"德普之... 大家好,今天小编来为大家解答德普之星透视辅助这个问题咨询软件客服可以免费测试直接加微信(136704...
开挂辅助安装"hhp... hhpoker软件可以玩吗开挂教程视频分享装挂详细步骤在当今的网络游戏中,hhpoker软件可以玩吗...
开挂辅助脚本"wep... wepoker轻量版辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
开挂辅助插件"hh ... hh poker软件开挂教程视频分享装挂详细步骤在当今的网络游戏中,hh poker软件作为一种经典...
开挂辅助脚本"aap... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
开挂辅助安装"wep... 开挂辅助安装"wepoker有透视功能吗"开挂(透视)辅助插件(有挂存在) 了解更多开挂安装加(13...
开挂辅助安装"pok... 您好:pokemmo脚本手机版这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
开挂辅助插件"wep... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...