question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How test component @Input() set foo(bar) method.

See original GitHub issue

I’m submitting a…


[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ x ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

On Stackoverflow I did not find support, so I have to write here. https://stackoverflow.com/questions/48681990/test-method-setter-input-angular-4-karma

Current behavior

I test my component:

`import {Component, Input} from ‘@angular/core’; import {CameraModel, VideoModel} from “…/…/models”; import {Translation, TranslationService} from “angular-l10n”; import {Utilities, ISODateTime} from “…/…/utilities/utilities”; import {Observable} from “rxjs”; import {DashboardService} from “…/…/services/dashboard/dashboard.service”; import {OverlayService} from “…/…/services/overlay/overlay.service”; import {DashboardVideoAddComponent} from “…/dashboard-video-add/dashboard-video-add.component”;

@Component({ selector: ‘dashboard-videos-list’, templateUrl: ‘dashboard-videos-list.component.html’, styleUrls: [‘dashboard-videos-list.component.scss’] }) export class DashboardVideosListComponent extends Translation { cameraFetching: boolean = false; utilities = Utilities;

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

constructor(translate: TranslationService,
            public dashboardService: DashboardService) {
    super(translate);
}

fetchVideos(camera) {
    return Observable.create(obs => {
        this.cameraFetching = true;
        this.dashboardService.portalVideoService.fetchByCameraId(camera.cameraId, true)
            .finally(() => this.cameraFetching = false)
            .subscribe(data => {
                this._camera.videos = data;
                this.videos = data;
                obs.next(data);
            }, err => {
                OverlayService.error(err['business_error_message'] || 'Could not load videos.');
                obs.error(err);
            });
    }).toPromise();
}

addVideo() {
    OverlayService.open(DashboardVideoAddComponent, (popup) => {
        popup.camera = this._camera;
    }).then(video => {
        if (video) {
            let newVideoDate = ISODateTime.getDate(video.dateStart);
            let ind = this._camera.videos.length;
            for (let i = this._camera.videos.length - 1; i >= 0; i--) {
                if (ISODateTime.getDate(this._camera.videos[i].dateStart) < newVideoDate) {
                    ind = i;
                }
            }
            this._camera.videos.splice(ind, 0, video);
        }
    });
}

updateAnalytics(): void {
    this.dashboardService.updateAnalytics.next(true);
}

changeView(type: string): void {
    this.dashboardService.videosListViewMode = type;
}

}`

Test:

`import {async, ComponentFixture, TestBed} from ‘@angular/core/testing’; import {DashboardVideosListComponent} from ‘./dashboard-videos-list.component’; import {DashboardService} from “…/…/services/dashboard/dashboard.service”; import {LocationsService} from “…/…/services/locations/locations.service”; import {ConfigService} from “…/…/services/config/config.service”; import {LocalService} from “…/…/services/local/local.service”; import {CamerasService} from “…/…/services/cameras/cameras.service”; import {PortalVideoService} from “…/…/services/portal-video/portal-video.service”; import {StorageVideoService} from “…/…/services/storage-video/storage-video.service”; import {WebCameraStreamService} from “…/…/services/web-camera-stream/web-camera-stream.service”; import {DictionariesService} from “…/…/services/dictionaries/dictionaries.service”; import {VideoAnalyticsService} from “…/…/services/video-analytics/video-analytics.service”; import {AuthModule} from “…/…/modules/auth/auth.module”; import {HttpModule} from “@angular/http”; import {TranslationModule} from “angular-l10n”; import {NgbModule, NgbTooltipModule} from “@ng-bootstrap/ng-bootstrap”; import {LoadableComponent} from “…/loadable/loadable.component”; import {CUSTOM_ELEMENTS_SCHEMA} from “@angular/core”; import {CameraModel} from “…/…/models/camera.model”;

describe(‘DashboardVideosListComponent’, () => { let component: DashboardVideosListComponent; let fixture: ComponentFixture<DashboardVideosListComponent>;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [
            DashboardVideosListComponent,
            LoadableComponent
        ],
        providers: [
            DashboardService,
            LocationsService,
            ConfigService,
            LocalService,
            CamerasService,
            PortalVideoService,
            StorageVideoService,
            WebCameraStreamService,
            DictionariesService,
            VideoAnalyticsService
        ],
        imports: [
            AuthModule,
            HttpModule,
            TranslationModule.forRoot(),
            NgbModule,
            NgbTooltipModule.forRoot()
        ],
        schemas: [
            CUSTOM_ELEMENTS_SCHEMA
        ]
    }).compileComponents();
}));

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

it('should be created', () => {
    expect(component).toBeTruthy();
});

it('should be defined', () => {
    expect(component).toBeDefined();
});

describe('changeView', () => {
    it('table', async(() => {
        component.changeView('table');

        expect(component.dashboardService.videosListViewMode).toBe('table');
    }));

    it('grid', async(() => {
        component.changeView('grid');

        expect(component.dashboardService.videosListViewMode).toBe('grid');
    }));
});

describe('updateAnalytics', () => {
    it('observable correct', async(() => {
        expect(component.dashboardService.updateAnalytics$.subscribe(
            data => {
                expect(data).toBe(true);
            }
        ));

        component.updateAnalytics();
    }));
});

describe('set camera', () => {
    it('success', async(() => {
        let expectVal = new CameraModel({cameraId: 13});
        component.camera(expectVal).then(() => {
            expect(component._camera['cameraId']).toBe(expectVal['cameraId']);
        });
    }));
});

});`

During the test set camera => success, I get an error: Failed: component.camera is not a function

Expected behavior

The test passes.

Minimal reproduction of the problem with instructions

At the moment, can’t provide

Environment

{
  "dependencies": {
    "@agm/core": "^1.0.0-beta.2",
    "@angular/animations": "4.4.6",
    "@angular/common": "4.4.6",
    "@angular/compiler": "4.4.6",
    "@angular/core": "4.4.6",
    "@angular/forms": "4.4.6",
    "@angular/http": "4.4.6",
    "@angular/platform-browser": "4.4.6",
    "@angular/platform-browser-dynamic": "4.4.6",
    "@angular/router": "4.4.6",
    "@ng-bootstrap/ng-bootstrap": "1.0.0-beta.5",
    "@swimlane/ngx-datatable": "^9.0.0",
    "@types/es6-promise": "0.0.32",
    "angular-l10n": "3.5.2",
    "angular2-jwt": "^0.2.3",
    "angular2-text-mask": "^8.0.3",
    "bootstrap": "4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "css-element-queries": "^0.4.0",
    "d3": "^4.11.0",
    "geojson": "^0.4.1",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "moment": "^2.19.1",
    "ng2-charts": "^1.6.0",
    "normalizr": "^3.2.4",
    "rxjs": "^5.1.0",
    "tether": "^1.4.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.2.7",
    "@angular/compiler-cli": "4.4.6",
    "@angular/language-service": "4.4.6",
    "@types/d3": "^4.11.0",
    "@types/jasmine": "2.5.45",
    "@types/node": "^6.0.90",
    "angular2-recaptcha": "^0.6.0",
    "bestzip": "^1.1.4",
    "codelyzer": "~3.0.1",
    "jasmine-core": "~2.6.2",
    "jasmine-spec-reporter": "~4.1.0",
    "karma": "~1.7.0",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-phantomjs-launcher": "^1.0.4",
    "protractor": "~5.1.2",
    "ts-node": "~3.0.4",
    "tslint": "~5.3.2",
    "typescript": "~2.3.3"
  }
}

Angular version: 4.4.6

Browser:
- [ ] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
- [ x ] karma-chrome-launcher version ~2.1.1
- [ x ] karma-phantomjs-launcher ^1.0.4
 
For Tooling issues:
- Node version: 8.6.0
- Platform:  Windows

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:1
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
matiasfs12commented, Sep 2, 2019

@whyboris It works like a charm ! You made my day, thank you

2reactions
whyboriscommented, Feb 14, 2019

Quick summary for everyone:

The magic is with async()

Component:

@Input()
set myVar(data: number) {
   this._myVar = data;
}

Test:

it('myVar input should set _myVar', async(() => {
  component.myVar = 42;
  expect(component._myVar).toBe(42);
}));
Read more comments on GitHub >

github_iconTop Results From Across the Web

How test component @Input() set foo(bar) method. : r/angular
I'm submitting a... Current behavior I test component: import {Component, Input} from '@angular/core'; import {CameraModel, ...
Read more >
Testing Components • Angular - codecraft.tv
We can test inputs by just setting values on a component's input properties. We can test outputs by subscribing to an EventEmitters observable...
Read more >
How to write unit testing for Angular / TypeScript for private ...
Eg. describe("Testing foo bar for status being set", function() { ... //Variable with type any let fooBar; fooBar = new FooBar(); ... //Method...
Read more >
Testing Workflow for Web Components - DEV Community ‍ ‍
Learn to test and debug your web component with open-wc tools so you can deploy or share your production-ready code with confidence.
Read more >
Passing parameters to components - bUnit
In tests written in .razor files, passing parameters is most easily done with inside an inline Razor template passed to the Render method,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found