我正在尝试将单元测试添加到我的Angular 2应用程序中.在我的一个组件中,有一个带有(click)处理程序的按钮.当用户单击该按钮时,将调用在.ts类文件中定义的函数.该函数在console.log窗口中打印一条消息,说明该按钮已被按下.我目前的测试代码测试打印console.log消息:
describe('Component: ComponentToBeTested', () => {
var component: ComponentToBeTested;
beforeEach(() => {
component = new ComponentToBeTested();
spyOn(console, 'log');
});
it('should call onEditButtonClick() and print console.log', () => {
component.onEditButtonClick();
expect(console.log).toHaveBeenCalledWith('Edit button has been clicked!);
});
});
Run Code Online (Sandbox Code Playgroud)
但是,这只测试控制器类,而不是HTML.我不只是想测试onEditButtonClick调用时发生的日志记录; 我还想测试onEditButtonClick当用户单击组件的HTML文件中定义的编辑按钮时调用.我怎样才能做到这一点?
我的组件中有一个包含a的close函数 setTimeout()以便给动画完成时间.
public close() {
this.animate = "inactive"
setTimeout(() => {
this.show = false
}, 250)
}
Run Code Online (Sandbox Code Playgroud)
this.show 必然是一个 ngIf.
this.animate 绑定动画.
我有一个需要测试此功能的测试
it("tests the exit button click", () => {
comp.close()
fixture.detectChanges()
//verifies the element is no longer in the DOM
const popUpWindow = fixture.debugElement.query(By.css("#popup-window"))
expect(popUpWindow).toEqual(null)
})
Run Code Online (Sandbox Code Playgroud)
如果有的话,你如何正确测试这个功能? setTimeout()?
我正在使用,jasmine.clock().tick(251)但窗户永远不会消失.对此有何想法?
我有一个Angular2组件,其中包含一个看起来像的选择框
<select [(ngModel)]="envFilter" class="form-control" name="envSelector" (ngModelChange)="onChangeFilter($event)">
<option *ngFor="let env of envs" [ngValue]="env">{{env}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我正在尝试为ngModelChange事件编写单元测试.这是我最近的失败尝试
it("should filter and show correct items", async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
el = fixture.debugElement.query(By.name("envSelector"));
fixture.detectChanges();
makeResponse([hist2, longhist]);
comp.envFilter = 'env3';
el.triggerEventHandler('change', {});
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(comp.displayedHistory).toEqual(longhist);
});
});
Run Code Online (Sandbox Code Playgroud)
我遇到问题的部分是更改底层模型的值comp.envFilter = 'env3';不会触发更改方法.我补充说el.triggerEventHandler('change', {});但是这个抛出了Failed: Uncaught (in promise): ReferenceError: By is not defined.我在文档中找不到任何提示......任何想法?
unit-testing typescript karma-jasmine angular2-testing angular
从文档中我们可以阅读:
waitForAsync(fn: Function): (done: any) => any
将测试功能包装在异步测试区中。当该区域内的所有异步调用完成后,测试将自动完成。可用于包装注入调用。
我不明白,什么时候使用waitForAsync函数?什么之间的区别waitForAsyncVS(async或fakeAsync)?
我知道async和fakeAsync方法设置了某种监听器,该监听器记录了所有异步操作,以便角度测试框架可以使用whenStable并tick()管理等待所有这些东西完成的过程。我认为那是正确的吗?
我努力理解的是,实际上执行顺序是否存在差异-因为如果没有,为什么要同时提供两者?
这使我学习了JS宏任务和Micro任务,我想知道这两种方法是否在此领域不同?