Set element height in PhantomJS

2019-01-25 09:37发布

问题:

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.

回答1:

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);
}));


回答2:

You could even remove the use of JqLite altogether and use raw DOM methods ...

var el = document.createElement('div');
el.textContent = "Lorem ipsum...";

document.body.appendChild(el); 

...