我有一个使用下面定义的 ElementRef
的方法。
@ViewChild('idNaicsRef') idNaicsRef: ElementRef;
ElementRef
然后使用 .nativeElement.focus()
设置焦点。
该方法在运行规范时失败,提示“undefined is an object”
最佳答案
尽管 httpNick 的回答应该有效,但我最终就此问题询问了我团队中的一位架构师,他引导我找到了一个略有不同的解决方案,该解决方案可能更简单一些。
describe(MyComponent.name, () => {
let comp: MyComponent;
describe('myFunction', () => {
it('calls focus', () => {
comp.idNaicsRef = {
nativeElement: jasmine.createSpyObj('nativeElement', ['focus'])
}
comp.myFunction();
expect(comp.idNaicsRef.nativeElement.focus).toHaveBeenCalled();
});
});
这个特殊的例子只是测试 focus
方法是否被调用。这是我在测试我的方法时感兴趣的测试,但您当然可以测试任何您想要的测试。关键是事先的设置(在向我展示之前这是难以捉摸的)。
关于javascript - 如何在 Angular 4 规范文件中模拟 nativeElement.focus(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48909043/