我的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请求?
答案 0 :(得分:2)
您不能通过new SomeComponent()
创建组件实例。组件需要由Angular创建,如tcb.createAsync(SomeComponent)
。如果myComponent
位于AutocompleteComponent
的模板中,则会从fixture
进行查询。