nativeElement.getBoundingClientRect() always returns 0 in Angular tests

Discussão em 'Angular' iniciado por Jeff Fairley, Outubro 21, 2024.

  1. Jeff Fairley

    Jeff Fairley Guest

    I have an Angular Component (5.2) that positions itself relative to the nativeElement.getBoundingClientRect() output of another element.

    In test, I have created a wrapper component with styles to simulate positioned elements, but the returned ClientRect is always all zeros.

    Is there a way to ask Angular to actually position my element in a DOM?

    For an illustration, here's my TestComponent. Internally the <popup> component will calculate it's fixed position using anchor.nativeElement.getBoundingClientRect().

    I don't think it's relevant, but I'm using Jest to execute the tests.

    I've tried with and 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);
    });
    });
    });

    Continue reading...

Compartilhe esta Página