【发布时间】:2016-08-08 19:52:27
【问题描述】:
有这个组件
import {Component} from 'angular2/core';
import { FORM_DIRECTIVES } from 'angular2/common';
@Component({
selector: 'something',
templateUrl: 'something.html',
providers: [],
directives: [FORM_DIRECTIVES],
pipes: []
})
export class Something {
constructor() { }
save(data) {
alert(data);
}
}
使用这个模板(something.html)
<form #myForm="ngForm" (ngSubmit)="save(myForm.value)">
<label for="title">Title</label>
<input id="title" type="text" ngControl="title" />
<label for="primaryImage">Primary Image</label>
<input id="primaryImage" type="text" ngControl="primaryImage" />
<button type="submit">Save</button>
</form>
还有这个测试
it('should call save method after clicking a Save button', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
return tcb.createAsync(Something).then((fixture) => {
spyOn(fixture.componentInstance, 'save');
fixture.detectChanges();
const compiled = fixture.nativeElement;
compiled.querySelector('#title').value = 'testTitle';
compiled.querySelector('#primaryImage').value = 'tabc.png';
compiled.querySelector('button').click();
expect(fixture.componentInstance.save).toHaveBeenCalledWith({
title: 'testTitle',
primaryImage: 'abc.png'
});
});
}));
测试失败,spy 没有调用 save 方法。 但是,当我在浏览器中手动尝试时,如果有效,则会显示警报。 当我使用 form.submit 代替 button.click 时,测试也失败了。
当我在按钮上使用(click)="save(myForm.value)" 而不是在表单上使用ngSubmit 时,测试仍然失败,但原因不同。在这种情况下已经调用了 spy 上的 Save 方法,但传递给它的数据是 {}。
谁能告诉我这里缺少什么?
【问题讨论】:
标签: javascript unit-testing angular