我有一个应用程序,可以在其中更改input
的值,并且应该立即更改h1
的值。手动测试(更改input
会更改h1
)时,它的效果很好,但在测试中无法正常工作(更改input
对{{1}的内容没有影响}。
我仔细检查了我在想想应该使用h1
和detectChanges
的时间,但我仍然没有运气。
有人可以发现我在做什么吗?
whenStable
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<form>
<input type="text" name="query-input" [(ngModel)]="myText" />
</form>
<h1>H1 content is "{{myText}}"</h1>
`
})
export class AppComponent implements OnInit {
public myText = 'Default value';
ngOnInit(): void {
this.myText = 'Value from ngOnInit';
}
}
因此,在倒数第二个import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should work', () => {
const fixture = TestBed.createComponent(AppComponent);
console.log(fixture.componentInstance.myText); // VALUE IS OK: "Default value"
fixture.detectChanges();
fixture.whenStable().then(() => {
console.log(fixture.componentInstance.myText); // VALUE IS OK: "Value from ngOnInit"
const compiled = fixture.debugElement.nativeElement;
compiled.querySelector('input').value = 'Value from test';
fixture.detectChanges();
fixture.whenStable().then(() => {
console.log(compiled.querySelector('input').value); // VALUE IS OK: 'Value from test'
console.log(fixture.componentInstance.myText); // VALUE IS UNEXPECTED: 'Value from ngOnInit'
console.log(compiled.querySelector('h1').textContent); // VALUE IS UNEXPECTED: 'H1 content is "Value from ngOnInit"'
});
});
});
});
中,我得到console.log
,但我希望得到Value from ngOnInit
使用的角度版本:7.2.0
答案 0 :(得分:1)
发现了问题,仅更改"GET /var/www/cgi-bin/folder/filename.py HTTP/1.1" 200 -
中的value
,然后需要调用input
。
所以这段代码:
dispatchEvent
需要更改为:
...
compiled.querySelector('input').value = 'Value from test';
fixture.detectChanges();
...