【发布时间】:2018-07-31 08:45:35
【问题描述】:
我有一个 Angular 组件 (5.2),它相对于另一个元素的 nativeElement.getBoundingClientRect() 输出定位自身。
在测试中,我创建了一个带有样式的包装器组件来模拟定位元素,但返回的ClientRect 始终全为零。
有没有办法让 Angular实际上在 DOM 中定位我的元素?
为了说明,这是我的TestComponent。在内部,<popup> 组件将使用anchor.nativeElement.getBoundingClientRect() 计算它的固定位置。
我认为这无关紧要,但我正在使用 Jest 执行测试。
我试过 with 和 without async().
@Component({
selector: 'test',
styles: [`
:host {
width: 1000px;
height: 1000px;
display: flex;
justify-content: center;
align-content: center;
}
`],
template: `
<button #button></button>
<popup [anchor]="button">
<div id="helloWorld">hello world</div>
</popup>
`
})
class TestComponent {
@ViewChild('button')
public buttonElement: ElementRef;
}
describe('test', () => {
let fixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [PopupModule]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
});
}));
it('should be positioned', () => {
const button = fixture.componentInstance.buttonElement.nativeElement;
// Either of these always fail, because the button is not positioned.
// I have also tried using fixed positioning of the button.
// this will fail
expect(button.getBoundingClientRect().top).not.toEqual(0);
// this will fail, too
return fixture.whenRenderingDone().then(() => {
expect(button.getBoundingClientRect().top).not.toEqual(0);
});
});
});
【问题讨论】:
-
我想这是一个时间问题。尝试在
beforeEach中创建组件并用async包围。 -
我更新了这个例子来说明
async()的用法 -
buttonElement.nativeElement存在吗?如果是这样,您可以尝试访问button.offsetHeight(只需访问它,无需对值执行任何操作),看看它是否会强制将按钮定位在页面中。 -
@JeffFairley 你解决了这个问题吗?我也有
-
没有。我相信这是一个 JSDOM 问题。可能是故意的,因为 IDK 计算 DOM 大小会带来什么成本。
标签: angular typescript jestjs