我使用 angular-cli 创建了一个简单的应用程序来说明我的问题。您可以在此处查看所有代码: https ://github.com/wholladay/tracking
每当单击包含元素时,该指令都会调用服务。因此,我想模拟该服务并确保在将点击事件发送到指令时调用它。
这是我的测试代码:
/* tslint:disable:no-unused-variable */
import { inject, addProviders } from '@angular/core/testing';
import { TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TrackingDirective } from './tracking.directive';
import { TrackingService } from './tracking.service';
class MockTrackingService extends TrackingService {
public eventCount = 0;
public trackEvent(eventName: string) {
this.eventCount++;
}
}
describe('TrackingDirective', () => {
let builder: TestComponentBuilder;
let mockTrackingService: MockTrackingService;
let trackingDirective: TrackingDirective;
beforeEach(() => {
mockTrackingService = new MockTrackingService();
trackingDirective = new TrackingDirective(mockTrackingService);
addProviders([
{provide: TrackingDirective, use: trackingDirective}
]);
});
beforeEach(inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
builder = tcb;
}));
// General button tests
it('should apply class based on color attribute', (done: () => void) => {
return builder.createAsync(TestApp).then(fixture => {
let testComponent = fixture.debugElement.componentInstance;
let buttonDebugElement = fixture.debugElement.query(By.css('button'));
buttonDebugElement.nativeElement.click();
expect(buttonDebugElement).toBeTruthy();
expect(mockTrackingService.eventCount).toBe(1);
done();
});
});
});
@Component({
selector: 'test',
template: `<button tracking="some button"></button>`,
directives: [TrackingDirective]
})
class TestApp {
}
这是我的指令代码:
import { Directive, HostListener, Input } from '@angular/core';
import { TrackingService } from './tracking.service';
@Directive({
selector: '[tracking]',
providers: [
TrackingService
]
})
export class TrackingDirective {
@Input() tracking: string;
constructor(private trackingService: TrackingService) {
}
@HostListener('click', ['$event.target'])
onClick(element) {
this.trackingService.trackEvent(this.tracking);
}
}
当我通过 运行测试时ng test
,测试失败,因为 eventCount 仍然是 0 而不是 1。