Làm cách nào để giả lập sự kiện nhấp của một hàm trong Angular 2? Đối với Hợp phần Trang chủ của tôi, tôi có:Góc 2 Jasmine Làm thế nào để kiểm tra chức năng của một thành phần
Home Component
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
moduleId: module.id,
templateUrl: 'home.component.html',
styleUrls: ['home.component.css'],
selector: 'home',
})
export class HomeComponent {
constructor(private router: Router) {
}
redirectToUpload() {
this.router.navigate(['/upload']);
}
redirectToAbout() {
this.router.navigate(['/about']);
}
}
Trang chủ Hợp phần đặc tả
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { HomeComponent } from './home.component';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { HomeModule } from './home.module';
import { RouterLinkStubDirective, RouterOutletStubComponent } from '../../../test/router-stubs';
import { RouterModule } from '@angular/router';
export function main() {
let de: DebugElement;
let comp: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
let mockRouter:any;
class MockRouter {
//noinspection TypeScriptUnresolvedFunction
navigate = jasmine.createSpy('navigate');
}
describe('Home component',() => {
// preparing module for testing
beforeEach(async(() => {
mockRouter = new MockRouter();
TestBed.configureTestingModule({
imports: [HomeModule],
}).overrideModule(HomeModule, {
remove: {
imports: [ RouterModule ],
},
add: {
declarations: [ RouterLinkStubDirective, RouterOutletStubComponent ],
providers: [ { provide: Router, useValue: mockRouter }],
}
}).compileComponents().then(() => {
fixture = TestBed.createComponent(HomeComponent);
comp = fixture.componentInstance;
});
}));
tests();
});
function tests() {
beforeEach(() => {
// trigger initial data binding
fixture.detectChanges();
de = fixture.debugElement.query(By.css('h1'));
});
it('can instantiate Home',() => {
expect(comp).not.toBeNull();
});
it('should have expected <h1> text',() => {
fixture.detectChanges();
const h1 = de.nativeElement;
expect(h1.innerText).toMatch("Home");
});
}
}
Tôi muốn thử nghiệm redirectToUpload() và redirectToAbout(). Làm thế nào tôi sẽ giả lập nhấp chuột và đảm bảo rằng chuyển hướng là dành cho liên kết được chỉ định?
Chúng tôi có thể gọi các bước trên bằng cách mô phỏng nhấp chuột không? – Aditya