Unit Testing a Custom Component with @Input


#1

How do you unit test a custom component with @Input. I’d like to test the template but how do you get to it? Angular.io says to use TestBed out of @angular/core/testing to get the component “fixture” but using that causes errors. What’s the {N} way to compile components for testing and access them? I know I can set the component property and check the property, but if I want to check an element in the template to make sure it got the right value or a value through a pipe then just set/checking the component property isn’t enough.

thanks


#2

I’m also having an issue incorporating TestBed in order to create tests for NativeScript NG2 components. Have you had any luck with this? I linked the code below that is giving me trouble. It should be a very simple test, but it’s turning out to be a headache.

Here is the component under test:

import { Component } from "@angular/core";

@Component({
    selector: "links",
    templateUrl: "./components/links/links.component.html"
})

export class LinksComponent {
    test = "test";

    public constructor() {
        
    }
}

And the test itself:

import "reflect-metadata";
import { LinksComponent } from "../../components/links/links.component";
import { ComponentFixture, TestBed } from '@angular/core/testing';

describe("Links Component", () => {

    let comp: LinksComponent;
    let fixture: ComponentFixture<LinksComponent>;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [ LinksComponent ],
        });

        fixture = TestBed.createComponent(LinksComponent);

        comp = fixture.componentInstance;
    });

    it("will pass because the app is run on an ios device", () => {
        expect(comp.test).toEqual("test");
    })
});

The log output is:

NativeScript / 10.3 (10.3; iPhone)  ../../tests/components/links.spec.js at line 0 FAILED
	ReferenceError: Can't find variable: Zone
NativeScript / 10.3 (10.3; iPhone): Executed 1 of 0 (1 FAILED) (0 secs / 0 seNativeScript / 10.3 (10.3; iPhone): Executed 1 of 0 (1 FAILED) ERROR (0.008 secs / 0 secs)
CONSOLE LOG file:///app/tns_modules/nativescript-unit-test-runner/main-view-model.js:258:24: NSUTR: completeAck
May 11 16:16:43 --- last message repeated 1 time ---
CONSOLE LOG file:///app/tns_modules/nativescript-unit-test-runner/main-view-model.js:90:28: NSUTR-socket.io: io server disconnect
CONSOLE LOG file:///app/tns_modules/nativescript-unit-test-runner/main-view-model.js:151:24: NSUTR: disregarding second execution
Test run failed.

#3

any news? Currently I’m on v4.0.0 and this error still remains!