如何模拟这行代码。我有一个带有任何类型主机属性的配置(即mockConfig)。但是它有html元素。这样我就可以使用querySelector和getBoundingClientRect方法了。但我不能嘲笑getBoundingClientRect。
//this.config.host='<div><i class="icon-dropdown"></i></div>'
..
const arrowHostLoc = (this.config.host as HTMLElement).querySelector('.icon-dropdown').getBoundingClientRect();我正在使用的代码
const mockConfig = {
contentType: TestComponent,
contentConfig: contentConfig,
cssClass: 'rainbow',
alignment: 'center',
topPadding: 5,
scrollListener: scrollSubject.asObservable(),
host: { //type of any
getBoundingClientRect: hostGetBoundClientRectSpy
}
} as IPopoverConfig;
--------------------
describe('xxx',()=>{
...
mockConfig.host = document.createElement('div');
spyOn('mockConfig.host.querySelector',['getBoundingClientRect']).and.returnValue(new DOMRect(0,0,0,0));
});但是我作为TypeError: Cannot read property 'getBoundingClientRect' of null收到了错误。
我做错了什么?
发布于 2019-09-04 13:54:01
而不是
spyOn('mockConfig.host.querySelector',['getBoundingClientRect']).and.returnValue(new DOMRect(0,0,0,0));我用过
spyOn(Element.prototype,['getBoundingClientRect']).and.callFake(
jasmine.createSpy('getBoundingClientRect').and.returnValue({ top: 1, height: 100, left: 2, width: 200, right: 202 })
);这解决了我的问题。谢谢
发布于 2019-09-03 18:15:39
您的主机没有querySelector。querySelector是未定义的,所以你也需要模拟它。
要么为主机显式提供HTMLElement的类型,以便它具有querySelector,要么像下面这样模拟它:
...
host :{
querySelector: {
getBoundingClientRect: hostGetBoundClientRectSpy
}
}https://stackoverflow.com/questions/57723979
复制相似问题