如何通过在我的spec文件中创建angular2组件的新实例来调用方法?

我有myComponent,其中包含method1,method2和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 .
//
}

这是该组件的html模板:

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

这是我的spec文件.我需要确保插入的任何值都转换为大写.

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");

                });
        }));
});

我希望值“g”设置为等于“g”,并检查调用method1()后返回“G”.

问题:

1.在创建myComponent的实例时,是否将fixture.nativeElement作为参数传递给对象?
2.另外,如果你可以帮我测试组件内部调用的$.JSON方法.如何模拟JSON请求?

最佳答案 您不需要通过新的SomeComponent()创建组件实例.组件需要由Angular创建,如tcb.createAsync(SomeComponent).如果myComponent位于AutocompleteComponent的模板中,则从fixture中查询它.

点赞