Alex Pereira
Alex Pereira

Reputation: 61

Test method setter @Input() Angular 4 Karma

How can I test this method from the component:

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

In the test, you need to give him my stub, but as I have not tried, it does not work...

Info

If I use setter as a method in the test, I get the error "component.camera is not a function"

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)

Test before each:

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

Test:

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

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

Upvotes: 5

Views: 7455

Answers (1)

yuffieh
yuffieh

Reputation: 186

Instead of

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

you want

component.camera = new CameraModel({});

Since it is an input setter you aren't really calling the function more that the function runs everytime you give it a new value. (:

Upvotes: 9

Related Questions