A
A
Alexander N++2018-02-01 17:11:00
JavaScript
Alexander N++, 2018-02-01 17:11:00

Headless chrome + mocha/chai testing, how to properly handle error?

If the test fails, I get an error

(node:9140) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: check is insert script: expected 2 to equal 1
(node:9140) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

which causes the chrome process to not close and the test to hang until the timeout
The test itself:
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');

const request = require('request');
const should = require('chai').should;
const assert = require('chai').assert;
const expect = require('chai').expect;
//const Benchmark = require('benchmark');
const nock = require('nock');
//const async = require('async');

finalhandler = require('finalhandler'),
http = require('http'),
Router = require('router');

async function launchChrome() {
    return await chromeLauncher.launch({
        chromeFlags: [
            // '--disable-gpu',
            // '--headless',
            '--use-mobile-user-agent',
            '--user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"',
            "--incognito",
            '--test-type',
            '--disable-translate',
            '--disable-extensions'
        ]
    });
}

async function getBrowserComponents() {
    return new Promise(async (resolve) => {
        const chrome = await launchChrome();
        const protocol = await CDP({
            port: chrome.port
        });
        const {
            DOM,
            Page,
            Emulation,
            Runtime
        } = protocol;
        await Promise.all([Page.enable(), Runtime.enable(), DOM.enable()]);

        return resolve({
            DOM,
            Page,
            Emulation,
            Runtime,
            protocol,
            chrome
        })
    })
}



describe('Visual test view chromium', function () {
    this.timeout(60000);

    let router = Router({});
    let server;
    let serverPort = 3067;
    // proxy var
    let DOM,
        Page,
        Emulation,
        Runtime,
        protocol,
        chrome;

    after(function () {
       protocol.close();
       chrome.kill();
    });
  
    before(function(done){

        let templateHeader = `
        <!DOCTYPE html>
                <html>
                <head>
                    <meta charset="UTF-8">
                    <title>TEST JS CODE</title>
                </head>
                <body>
        `;
        let templateFooter = `</body></html>`;


        router.get('/',function(req, res) {
            res.end('');
        });

        router.get('/test-js',function(req, res) {

           res.end(templateHeader + `
                   <script type="text/javascript"></script>
                   <script type="text/javascript"></script>
                   ` + templateFooter);

        });
        server = http.createServer(function onRequest(req, res) {
            router(req, res, finalhandler(req, res));
        });
        server.listen({port: serverPort, timeout: 60000}, function(){
            console.log('server start');

            // set proxy var
            (async function() {
                let lib =  await getBrowserComponents();
                DOM = lib.DOM;
                Page = lib.Page;
                Emulation = lib.Emulation;
                Runtime = lib.Runtime;
                protocol = lib.protocol;
                chrome = lib.chrome;

                done();
            })()

        });
    });
    
    it('test safe code', function (done) {

         (async function() {
             let url = 'http://localhost:'+serverPort+'/test-js';

             await Page.navigate({ url: url, referrer: 'http://test-site.ru' });

             Page.loadEventFired(async() => {
                 let scriptJS = `document.querySelectorAll('script').length`;
                 let result = await Runtime.evaluate({
                     expression: scriptJS
                 });
                 expect(result.result.value).to.equal(1, "check is insert script");
                 done();
             });

         })();

    })

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander N++, 2018-02-01
@sanchezzzhak

small solution, but it only works for 1 test it(*

it('test safe code', function (done) {
        (async () =>{
            let url = 'http://localhost:'+serverPort+'/test-js';
            await Page.navigate({ url: url, referrer: 'http://test-site.ru' });
            Page.loadEventFired(async() => {
                let scriptJS = `document.querySelectorAll('script').length`;
                let result = await Runtime.evaluate({
                    expression: scriptJS
                });
                try {
                    expect(result.result.value).to.equal(1, "is insert script count 2?");
                } catch(e){
                    return done(e);
                }
                return done();
            });
        })();

    });

Since a shitty cloud of promises is spinning inside the asynchronous function, which are too lazy to understand, all checks need to be concluded with a try catch and an error must be returned in the callback of the test.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question