I'm trying to create an attribute directive that will catch click events and report them to our reporting service. I've followed the attribute directives guide and ended up with this:
@Directive({
selector: '[mtTrack]'
})
export class MtTrackDirective {
private _eventData: any;
constructor(private trackingService: TrackingService) {}
@Input('mtTrack') eventName: string;
@Input('mtTrackEvent') set mtTrackEvent(data: any) {
this._eventData = data;
}
@HostListener('click') onClick() {
this.trackingService.track(this.eventName, this._eventData)
}
}
I then try to test it with this test:
describe('MatificTrackDirective', () => {
@Component({
selector: 'test-cmp',
template: `<div [mtTrack]="'fakeEvent'" [mtTrackEvent]="{test: 'fake data'}"></div>`,
viewProviders: [MatificTrackDirective]
})
class TestComponent {}
let trackingMock;
let fixture: ComponentFixture<TestComponent>;
let debugElement : DebugElement;
let hostComp;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent, MatificTrackDirective],
providers: [{provide: TrackingService, useValue: mockClass(TrackingService)}]
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
hostComp = fixture.componentInstance;
debugElement = fixture.debugElement.query(By.directive(MatificTrackDirective));
trackingMock = debugElement.injector.get(TrackingService)
})
describe("HANDLERS", () => {
describe("onclick", () => {
When(() => {
debugElement.triggerEventHandler('click', {});
fixture.detectChanges();
});
Then(() => expect(trackingMock.track).toHaveBeenCalledWith('fakeEvent', {test: 'fake data'}));
});
});
});
But my trackingMock
is being called with [undefined, undefined]
instead of the values in the template. Any idea what is wrong?
I'm using Angular 2.2.1.