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可以透视码... 日前!wepoker可以透视码,佛手在线大菠萝技巧,方式教程(有挂助手)-哔哩哔哩1、完成佛手在线大...
现就发布提示!wejoker免... 现就发布提示!wejoker免费脚本(透视)一直确实有挂(有挂透明挂开挂辅助下载)-哔哩哔哩一、we...
现场直击!wepoker私人局... 现场直击!wepoker私人局透视插件,xpoker透视辅助,技法教程(有挂教程)-哔哩哔哩1、在w...
于此同时!hhpoker辅助码... 于此同时!hhpoker辅助码怎么用(透视)果然真的有挂(有挂方略开挂辅助平台)-哔哩哔哩1、在hh...
备受关注的!wepoker买钻... 备受关注的!wepoker买钻石有用吗,wepoker一直输的号能继续打吗,要领教程(有挂秘诀)-哔...
据文件显示!哈糖大菠萝助手(透... 据文件显示!哈糖大菠萝助手(透视)果然是有挂的(有挂助手开挂辅助神器)-哔哩哔哩;1、哈糖大菠萝助手...
现就发布提示!aapoker俱... 现就发布提示!aapoker俱乐部靠谱吗,wepoker模拟器哪个,模块教程(有挂攻略)-哔哩哔哩1...
据相关数据显示!wepoker... 据相关数据显示!wepoker透视苹果系统(透视)一贯真的有挂(确实有挂开挂辅助安装)-哔哩哔哩1、...
推出新举措!wepoker辅助... 推出新举措!wepoker辅助器怎么弄,aapoker辅助器是真的吗,绝活教程(有挂细节)-哔哩哔哩...
出乎意料的是!哈糖大菠萝攻略(... 出乎意料的是!哈糖大菠萝攻略(透视)其实真的是有挂(了解有挂开挂辅助安装)-哔哩哔哩该软件可以轻松地...