Тестирование события прокрутки с Jasmine, Karma и PhantomJS - PullRequest
0 голосов
/ 16 апреля 2019

Я использую 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 Я также пытаюсь установить размер области просмотра, который, кажется, не имеет большого эффекта.

Любая помощь, которую я могу получить, будет чрезвычайно признательна.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...