使用Jasmine,Karma和PhantomJS测试滚动事件

时间:2019-04-16 11:55:07

标签: javascript jasmine phantomjs karma-jasmine gulp-karma

我正在将Jasmine与Karma和PhantomJS结合使用来测试我的代码,而我正经历一场噩梦,试图弄清楚如何测试某些滚动功能。

我有一些执行以下操作的功能。用户单击图像,添加zoomed类,然后用户垂直滚动70px以上,删除zoomed类。

这是我要测试的代码。

karma.conf.js

var webpackConfig = require('./webpack.karma.js')

module.exports = function(config) {

    config.set({
        frameworks: ['jasmine'],
        reporters: ['spec'],
        browsers: ['PhantomJSCustom'],
        customLaunchers: {
            'PhantomJSCustom': {
                base: 'PhantomJS',
                options: {
                    viewportSize: {
                        width: 1920,
                        height: 1080
                    },
                }
            }
        },
        files: [
            'src/**/*.spec.js'
        ],
        preprocessors: {
            'src/**/*.spec.js': ['webpack', 'babel']
        },
        random: false,
        webpack: webpackConfig,
        webpackMiddleware: {
            noInfo: true, //please don't spam the console when running in karma!
            stats: {
                chunks: false
            }
        },
        reporters: ['progress', 'junit'],
        junitReporter: {
            outputDir: './test-results', // results will be saved as $outputDir/$browserName.xml
            outputFile: 'tests.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile
            useBrowserName: false,
        }
    });
};

test.spec.js

const imageTemplate = require('../../02-basics/images/images.hbs');

import ZoomIn from './zoomIn';

function click(element){
    var event = document.createEvent('MouseEvent');
    event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(event);
}

function keyPress(key) {
    var event = document.createEvent('Event');
    event.keyCode = key; // Deprecated, prefer .key instead.
    event.key = key;
    event.initEvent('keydown');
    document.dispatchEvent(event);
}

function buildImage(imageData) {
    const image = imageTemplate(imageData);
    return image;
}

function removeImage() {
    const row = document.body.querySelectorAll('.row');
    for(var i = 0; i < row.length; i++) {
        if(row[i] !== null) {
            row[i].remove();
        }
    }
}

describe("An image", function() {

    beforeAll(function() {
        this.imageData =  {"altText": "Alt Text", "src": "/img/components/image/default/man-fishing/man-fishing-medium.jpg", "placeholderSrc": "/img/components/image/default/man-fishing/man-fishing-placeholder.jpg", "placeholderMobileSrc": "/img/components/image/default/man-fishing/man-fishing-placeholder-small.jpg", "sources": [{"media": "(max-width: 320px)","src": "/img/components/image/default/man-fishing/man-fishing-extra-small.webp","type": "image/webp"},{"media": "(max-width: 320px)","src": "/img/components/image/default/man-fishing/man-fishing-extra-small.jpg","type": "image/jpg"},{"media": "(max-width: 543px)","src": "/img/components/image/default/man-fishing/man-fishing-small.webp","type": "image/webp"},{"media": "(max-width: 543px)","src": "/img/components/image/default/man-fishing/man-fishing-small.jpg","type": "image/jpg"},{"media": "(max-width: 767px)","src": "/img/components/image/default/man-fishing/man-fishing-medium.webp","type": "image/webp"},{"media": "(max-width: 767px)","src": "/img/components/image/default/man-fishing/man-fishing-medium.jpg","type": "image/jpg"},{"media": "(max-width: 1023px)","src": "/img/components/image/default/man-fishing/man-fishing-large.webp","type": "image/webp"},{"media": "(max-width: 1023px)","src": "/img/components/image/default/man-fishing/man-fishing-large.jpg","type": "image/jpg"},{"media": "(min-width: 1024px)","src": "/img/components/image/default/man-fishing/man-fishing-extra-large.webp","type": "image/webp"},{"media": "(min-width: 1024px)","src": "/img/components/image/default/man-fishing/man-fishing-extra-large.jpg","type": "image/jpg"}],"caption": "Caption - Water is a transparent nearly colorless chemical substance"};
        this.imageContainer = '<div class="row"><div class="columns small-12 medium-8 medium-push-2"><div data-module="zoom-in"><div class="image--center spacer-l"></div></div></div>';
    });

    beforeEach(function(done) {
        document.body.insertAdjacentHTML( 'beforeend', this.imageContainer );

        const image = buildImage(this.imageData);
        const imageContainer = document.body.querySelector('.image--center');
        imageContainer.insertAdjacentHTML( 'beforeend', image );
        ZoomIn.init();

        setTimeout(function() {
            done();
        }, 300)
    });

    afterEach(function() {
        removeImage();
    });

    it("removes the zoom class when scrolled", function(done) {
        document.body.insertAdjacentHTML( 'beforeend', '<div style="height: 10000px"></div>' );
        document.body.style.height = '3000px';
        document.body.style.width = '1024px';
        const picture = document.body.querySelectorAll('picture')[1];
        const module = document.body.querySelector('[data-module="zoom-in"]');
        click(module);

        setTimeout(function() {
            console.log(window.innerHeight);
            console.log(window.innerWidth);
            console.log(window.pageYOffset);
            window.scrollTo(0, 500);
            console.log(window.pageYOffset);
            console.log(screen);
        }, 500);

        setTimeout(function() {
            console.log(window.pageYOffset);
            const hasZoomedClass = picture.classList.contains('zoomed');
            expect(hasZoomedClass).not.toBeTruthy();

            done();
        }, 1000);
    });

});

您可以在其中看到的console.logs产生以下结果: console.log(window.innerHeight); = 10072

console.log(window.innerWidth); = 1920

console.log(window.pageYOffset); = 0

// Do scrollTo() here

console.log(window.pageYOffset); = 0

console.log(screen); = Object{availTop: 0, width: 1024, availHeight: 768, height: 768, availWidth: 1024, colorDepth: 32, availLeft: 0, pixelDepth: 32}

据我所知,因为window.innerHeight始终设置为没有滚动内容的完整文档高度。我尝试使用window.resizeTo(),因此可以设置窗口大小,但这不起作用。您还可以在karma.conf.js中看到,我也在尝试设置视口大小,但这似乎并没有太大影响。

我能得到的任何帮助都会非常感激。

0 个答案:

没有答案