我有一个简单的应用程序有1个输入:
@Component({ selector: 'mycomponent', styles: [
], template: `
<div class="new-stuff">
<div>
<div>
Name: <input type="text" class="new-stuff-name" [(ngModel)]="stuff.name"/>
</div>
<div class="new-stuff-name-error" *ngIf="nameError != null">
{{nameError}}
</div>
</div>
<button class="new-stuff-save" (click)="checkStuff()">Add idea</button>
</div> `, })
export class StuffComponent implements OnInit {
public stuff = {name: ''};
public allStuff = [];
public checkStuff() {
if (this.stuff.name.length === 0) {
this.nameError = 'The name field cannot be empty';
}
if (this.stuff.name.length > 0) {
this.allStuff.push(this.stuff);
this.stuff= { name: ''};
}
}
}
当我运行应用程序时,我看到值发生了变化,所有内容看起来都捆绑在了一起,但当我尝试测试时,当我更改输入框中的值并单击按钮时,不显示错误消息,错误消息仍然是显示,因为输入值不会改变。
这是我的Jasmine测试:
describe(`stuff`, () => {
let comp: StuffComponent ;
let fixture: ComponentFixture<StuffComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [StuffComponent ],
schemas: [NO_ERRORS_SCHEMA],
imports: [FormsModule],
}).compileComponents();
fixture = TestBed.createComponent(StuffComponent );
comp = fixture.componentInstance;
}));
describe('adding a new stuff', () => {
let stuffNameInput;
let saveButton;
beforeEach(() => {
stuffNameInput = fixture.nativeElement
.querySelectorAll('.new-stuff-name')[0];
saveButton = fixture.debugElement.nativeElement.querySelector(
'.new-stuff-save');
});
describe('when is successfull', () => {
beforeEach(async(() => {
stuffNameInput.value = 'New Stuff';
stuffNameInput.dispatchEvent(new Event('input'));
saveButton.click();
fixture.detectChanges();
}));
it('should display an error', () => {
let errorDiv = fixture.nativeElement
.querySelectorAll('.new-stuff-desc-error');
expect(errorDiv.length)
.toBe(0, 'Error message displayed');
});
});
});
});
我尝试了多种方法,用fakeAsync替换async,调用tick函数,在fixture.whenStable()中移动click。然后阻塞,将div的检查移动到fixture.whenStable()。然后阻止。到目前为止没有任何工作。
我正在使用角度
的版本4.1.3
答案 0 :(得分:1)
回答我自己的问题来记录问题。
使用stuff.name作为ngModel效果不佳。
我将stuff.name更改为name并开始工作
答案 1 :(得分:0)
我发现mousedown比click()更适合我的测试:
const e: Event = document.createEvent('HTMLEvents');
e.initEvent('mousedown', false, true);
itemElements[1].nativeElement.dispatchEvent(e);