Angular 2属性指令 - 输入未定义

时间:2016-12-19 09:07:34

标签: angular angular2-directives

我正在尝试创建一个属性指令,用于捕获点击事件并将其报告给我们的报告服务。我跟着attribute directives guide并最终得到了这个:

@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)
    }
}

然后我尝试用这个测试来测试它:

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'}));
        });
    });
});

但我的trackingMock是使用[undefined, undefined]而不是模板中的值调用的。知道什么是错的吗?

我正在使用Angular 2.2.1。

0 个答案:

没有答案