How can I call methods by creating a new instance of the angular2 component in my spec file?

I have myComponent which contains method1, method2and ngOnInit.

export class myComponent  {

//input and output declaration

public myVar;
constructor( @Inject(ElementRef) private elementRef: ElementRef) {

}
public method1() { return this.myVar.val().toUpperCase(); }
public method2() { return this.myVar .val(""); }
public ngOnInit() {

this.myVar = //calling jQuery autocomplete method which in turns calls $.JSON () to get data .
//
}

here is the html template for this component:

<input type="text" value="{{symbol}}" size="{{size}}" maxlength="94"><span></span>

here is my specification file. I need to make sure the inserted value is converted to uppercase.

describe('myComponent Component', () => {
    beforeEachProviders(() => [myComponent, provide(ElementRef, { useValue: new MockElementRef() })]);
    class MockElementRef implements ElementRef {
        nativeElement = {};
    }

    it('should check uppercase conversion',inject([TestComponentBuilder, myComponent , ElementRef], (tcb:TestComponentBuilder) => {
            tcb.createAsync(myComponent)
                .then((fixture) => {
                    const element = fixture.nativeElement.firstChild;
                    element.setAttribute("value", "g");
                    element.setAttribute("size", 12); //setting size and value for input element
                    var getMyElem= $(element);

                    let ac= new myComponent(fixture.nativeElement); 

                    ac.ngOnInit(); //undefined
  //ac.method1(); unable to call
                    console.log(myComponent.prototype.method1()); //it calls value method but outputs cannot read val of undefined                     
                    expect(element.getAttribute("value")).toBe("G");

                });
        }));
});

I want the value of "g" to be set to "g", and also checks that "G" is returned after the call method1().

Questions:

1.Is passing fixture.nativeElement as a parameter when instantiating myComponent on the right?
2. Also, if you can help me verify the $ .JSON method called inside the component. How to mock a JSON request?

+4
1

new SomeComponent(). Angular tcb.createAsync(SomeComponent). myComponent AutocompleteComponent, fixture.

+2

All Articles