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

如何通过在规范文件中创建angular2组件的新实例来调用方法?,angular,angular2-testing,Angular,Angular2 Testing,我有一个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(); } p

我有一个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>
我希望将值“g”设置为等于“g”,并检查调用
method1()
后是否返回了“g”

问题:

1.创建myComponent实例时是否将fixture.nativeElement作为参数传递给right?

2.另外,如果您能帮助我测试组件内部调用的$.JSON方法。如何模拟JSON请求?

您不能通过
新建SomeComponent()
创建组件实例。组件需要像tcb.createAsync(SomeComponent)一样由Angular创建。如果
myComponent
AutocompleteComponent
的模板中,那么可以从
fixture

查询它。请查看编辑的代码。我只有一个组件(
myComponent
)。没有
自动完成组件
您的代码中仍然有
新的myComponent()
。这应该做什么?我猜他想为myComponent创建一个新实例,并在其上调用method1,method2。看起来像:D,但正如前面提到的那样,以这种方式创建组件通常没有多大意义。当然,您可以通过测试来测试方法,但是没有视图,因此也没有HTML。对我来说,这在问题的代码中没有意义。我想我开始明白问题所在了
createAsync(myComponent)
已经创建了一个
myComponent()
,无需使用
new myComponent()
再次创建它。只需使用fixture.debugElement.componentInstance访问类实例。您可能需要调用
fixture.detectChanges()
来调用更改检测,并调用
ngOnInit()
,如果您进行了需要更改检测处理的更改,也可能需要调用。
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");

                });
        }));
});