测试方法setter @Input()Angular 4 Karma

时间:2018-02-08 09:31:38

标签: angular unit-testing testing karma-runner

如何从组件中测试此方法:

@Input() set camera(camera: CameraModel) {
    this._camera = camera;
    if (this._camera && this._camera.cameraId) {
        this.fetchVideos(this._camera);
    }
}

在测试中,你需要给他我的存根,但是我没试过,它不起作用......

信息

如果我在测试中使用setter作为方法,我会得到错误" component.camera不是函数"

TypeError: component.camera is not a function
at Object.eval (webpack:///D:/dev/nighthawk/frontend/src/app/components/dashboard-videos-list/dashboard-videos-list.component.spec.ts?:86:23)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:392:26)
at AsyncTestZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/async-test.js?:49:39)
at ProxyZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/proxy.js?:76:39)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:391:32)
at Zone.runGuarded (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:155:47)
at runInTestZone (webpack:///D:/dev/nighthawk/frontend/~/@angular/core/@angular/core/testing.es5.js?:128:25)
at Object.eval (webpack:///D:/dev/nighthawk/frontend/~/@angular/core/@angular/core/testing.es5.js?:67:13)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:392:26)
at ProxyZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/proxy.js?:79:39)

每个人之前进行测试:

beforeEach(() => {
    fixture = TestBed.createComponent(DashboardVideosListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

测试:

describe('set camera', () => {
    it('success', async(() => {
        component.camera(new CameraModel({
            cameraId: 13
        }));

        expect(component._camera['cameraId']).toBe(13);
    }));
});

1 个答案:

答案 0 :(得分:1)

代替

   component.camera(new CameraModel({
       cameraId: 13
   }));

您想要的

component.camera = new CameraModel({});

由于它是输入设置器,所以您每次给它赋予新值时并不会真正调用该函数,而是使函数运行。 (: