gpt4 book ai didi

unit-testing - Angular 2 单元测试无法找到 debugElement

转载 作者:太空狗 更新时间:2023-10-29 17:39:40 24 4
gpt4 key购买 nike

我正在尝试在我的组件上运行单元测试,这是我的路由器的输出。我已经 stub 了组件使用的路由器和服务,我正在尝试使用 fixture.debugElement 拉取元素以确认测试正在运行。然而,这总是返回 NULL。

测试

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { HeroesComponent } from './heroes.component';
import { HeroService } from '../hero.service';
import { StubHeroService } from '../testing/stub-hero.service';
import { StubRouter } from '../testing/stub-router';

let comp: HeroesComponent;
let fixture: ComponentFixture<HeroesComponent>;
let de: DebugElement;
let el: HTMLElement;

describe('Component: Heroes', () => {

beforeEach( async(() => {
TestBed.configureTestingModule({
declarations: [HeroesComponent],
providers: [
{ provide: HeroService, useClass: StubHeroService },
{ provide: Router, useClass: StubRouter }
]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(HeroesComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('*'));
console.log(de);
el = de.nativeElement;
});
}));

it('should create an instance', () => {
expect(comp).toBeTruthy();
});

it('should update the selected hero', () => {
comp.onSelect({
id: 0,
name: 'Zero'
});
fixture.detectChanges();

expect(el.querySelector('.selected').firstChild.textContent).toEqual(0);
});
});

stub 路由器

export class StubRouter {
navigateByUrl(url: string) { return url; }
}

最佳答案

在查询元素之前调用fixture.detectChanges

fixture = TestBed.createComponent(HeroesComponent);
comp = fixture.componentInstance;

//call detect changes here
fixture.detectChanges();

de = fixture.debugElement.query(By.css('*'));
console.log(de);
el = de.nativeElement;

关于unit-testing - Angular 2 单元测试无法找到 debugElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40132281/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com