我有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>
这是我的规范文件。我需要确保插入的任何值都转换为大写。
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.Is 在创建myComponent实例时将fixture.nativeElement作为参数传递吗?
2.另外,如果您可以帮助我测试$ 。在组件内部调用的 JSON 方法。如何模拟 JSON 请求?
您不会通过 new SomeComponent()
创建组件实例。组件需要像tcb.createAsync(SomeComponent)
一样由 Angular 创建。如果myComponent
在AutocompleteComponent
的模板中,则从fixture
查询它。