问题
I have a method which uses an ElementRef
which is defined below.
@ViewChild('idNaicsRef') idNaicsRef: ElementRef;
ElementRef
then sets the focus using .nativeElement.focus()
.
The method fails while running the spec, saying 'undefined is an object'
回答1:
this should work. this just creates a spy object and then you can populate it with whatever you want, so you could even check if it was called in your unit test.
import createSpyObj = jasmine.createSpyObj;
comp.idNaicsRef = createSpyObj('idNaicsRef', ['nativeElement']);
comp.idNaicsRef.nativeElement = { focus: () => { }};
comp
is the reference to the component you are testing.
createSpyObj
comes from a jasmine import
回答2:
Although httpNick's answer should work, I ended up asking an architect on my team about this and he led me to a slightly different solution that may be a bit simpler.
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();
});
});
This particular example would just test to see if the focus
method has been called or not. That's the test that I was interested in when I was testing my method, but you could of course test whatever you wanted. The key is the setup beforehand (which was elusive before it was shown to me).
来源:https://stackoverflow.com/questions/48909043/how-to-mock-a-nativeelement-focus-in-angular-4-spec-file