Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set element height in PhantomJS

How do I set element height while testing in PhantomJS?

I'm testing on Karma using Jasmine framework and running on PhantomJS headless browser. I'm trying to test an AngularJS directive concerned with "infinite scrolling" (automated loading of items when user scrolls near to the bottom of the container element). I'm not using jQuery, nor do I wish to (unless there's no other way). I'm using .clientHeight, .scrollTop, and .scrollHeight properties. My directive works as expected, at least in Chrome.

I tried setting up a test for my directive, but I can't find a way to create element with non-zero height. The following code gives me no joy:

describe('something', function () {
    it('works with element height', inject(function ($document) {
        var el = angular.element('<div>Lorem ipsum...</div>')[0];
        $document.append(el);
        // size of non-empty block element should be non-zero by default
        expect(el.clientHeight).not.toBe(0);
        expect(el.scrollHeight).not.toBe(0);
        // it should certainly be non-zero after the height is set manually
        el.style.height = '999px';
        expect(el.clientHeight).not.toBe(0);
        expect(el.scrollHeight).not.toBe(0);
    }));
});

What am I doing wrong? Is it possible to do what I'm trying to do?

Short Answer

Setting the element height using element.style.height works just fine. I just didn't append the element correctly into the document body.

like image 810
hon2a Avatar asked May 02 '14 13:05

hon2a


1 Answers

I think the problem is with $document. You need to define which document and find the body element and attach to that. This code passes for me now in PhantomJS, by replacing $document with angular.element($document[0].body).

it('works with element height', inject(function ($document) {
    var el = angular.element('<div>Lorem ipsum...</div>')[0];

    //Find the correct body element
    angular.element($document[0].body).append(el);

    // size of non-empty block element should be non-zero by default
    expect(el.clientHeight).to.not.equal(0);
    expect(el.scrollHeight).to.not.equal(0);
    // it should certainly be non-zero after the height is set manually
    el.style.height = '999px';
    expect(el.clientHeight).to.not.equal(0);
    expect(el.scrollHeight).to.not.equal(0);
}));
like image 112
Jon Avatar answered Oct 15 '22 07:10

Jon