我需要测试此功能
getMainHeaderHeight(): number {
const header = <HTMLElement>this.getMainHeaderElement();
return header instanceof Element ? header.offsetHeight : 0;
}
但是发生的是,在我的单元测试中,我无法模拟函数 getMainHeaderElement()的输出,并且该类不是 Element 的实例,并且相对测试失败header instanceof Element
为假,因此函数返回的值为0而不是
elementHeight
import { DomService } from './dom.service';
describe('DomService', () => {
let service: DomService;
const elementHeight = 100;
let element: any;
beforeEach(() => {
service = new DomService();
function Element() {
this.offsetHeight = elementHeight;
}
element = new (Element as any);
element.innerHTML = 'text';
});
describe('#getMainHeaderHeight', () => {
it('should return the main header element height', () => {
let getMainHeaderElementSpy = jasmine.createSpy('getMainHeaderElement');
getMainHeaderElementSpy.and.returnValue(<Element>element);
service['getMainHeaderElement'] = getMainHeaderElementSpy;
const mainHeaderHeight = service.getMainHeaderHeight();
expect(mainHeaderHeight).toEqual(elementHeight);
});
});
});
是否有办法对此进行测试?或者我走错了方向?
预先感谢