且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Angular 2 Jasmine 如何测试组件的功能

更新时间:2023-10-30 16:50:40

首先,我建议你用 Typescript 编写测试,它可以保持组件和测试之间的内聚.

First, I recommend you writing your test in Typescript, it keeps cohesion between your components and your tests.

以下是规范文件中的基本步骤:

Here are the basic steps in your spec file:

获取元素(如果可能,我建议使用 Id 标签)

Get the element (I recommend using an Id tag if possible)

const element = fixture.debugElement.query(By.css("#your-element"));

触发事件.注意:元素上必须有 (click) 事件

Trigger the event. NOTE: there must be a (click) event on the element

element.triggerEventHandler("click", null);

然后从事件中检测变化

fixture.detectChanges();

在您的 HTML 模板中,您需要将点击事件指向您希望测试的函数 (click)="redirectToUpload()"

In your HTML template, you would need to have click events pointed at the functions you wish to test (click)="redirectToUpload()"