gpt4 book ai didi

angular - 在 Angular/Jasmine 单元测试中绕过 *ngIf

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

仅供引用,在 github 上记录了一个问题,还在错误中包含了 plunkr 的详细信息:https://github.com/angular/angular/issues/19292

我根本无法通过 ngIf 来检查值。如果我删除 ngIf 它工作正常。为了尝试解决这个问题,我直接在 beforeEach() 中硬编码了大使的值。但无济于事,我错过了其他东西。

在 HTML 中:

 <h3 class="welcome" *ngIf="ambassador"><i>{{ambassador.username}}</i></h3>

Jasmine :

beforeEach(() => {

TestBed.configureTestingModule({
declarations: [ ProfileComponent, BannedComponent ],
providers: [ HttpClient, {provide: AmbassadorService, useClass: MockAmbassadorService } ],
imports: [ RouterTestingModule, FormsModule, HttpClientModule ]
});

fixture = TestBed.createComponent(ProfileComponent);
component = fixture.componentInstance;

// AmbassadorService actually injected into the component
ambassadorService = fixture.debugElement.injector.get(AmbassadorService);
componentUserService = ambassadorService;
// AmbassadorService from the root injector
ambassadorService = TestBed.get(AmbassadorService);

// set route params
component.route.params = Observable.of({ username: 'jrmcdona' });
component.ambassador = new Ambassador('41', '41a', 'jrmcdona', 4586235, false);
component.ngOnInit();
});

it('should search for an ambassador based off route param OnInit', () => {
de = fixture.debugElement.query(By.css('.welcome'));
el = de.nativeElement;
fixture.detectChanges();
const content = el.textContent;
expect(content).toContain('jrmcdona', 'expected name');
});

最佳答案

问题是 DOM 在您手动检测更改之前不会更新,并且您试图在 *ngIf 呈现之前查询 DOM(并且 ambassador 值为检测到)。

  it('should search for an ambassador based off route param OnInit', () => {
fixture.detectChanges();
de = fixture.debugElement.query(By.css('.welcome'));
el = de.nativeElement;
const content = el.textContent;
expect(content).toContain('jrmcdona', 'expected name');
});

detectChanges() 移动到 query() 之前应该可以解决问题。

关于angular - 在 Angular/Jasmine 单元测试中绕过 *ngIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46363655/

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