Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...