繁体   English   中英

摩卡咖啡之前的作用域问题

[英]Scoping issue with before in Mocha

我在Mocha测试beforeafter方法中面临有关测试设置和清理的问题。

我正在使用Chromeless进行e2e测试。 为了更容易实现,我通过导出async函数将chrome启动器移动到了一个单独的文件(例如my-chrome-launcher.js ):

var chromeLauncher = require('chrome-launcher');

module.exports = {
    launchChrome: async function(headless) {
        try {
            var flags = ['--disable-gpu'];

            if (headless) {
                flags = ['--headless', '--disable-gpu'];
            }

            let chrome = await chromeLauncher.launch({
                port: 9222,
                chromeFlags: flags
            });

            console.log(`Chrome debugging running on port ${chrome.port} with pid ${chrome.pid}`);
            return chrome;
        } catch (ex) {
            console.error(ex.messsage);
        }
    }
}

simple.js

const {
    Chromeless
} = require('Chromeless')
var http = require('http');
var fs = require('fs');
var assert = require('assert');
const myChromeLauncher = require('./my-chrome-launcher.js');

describe('app', function() {

    describe('Top Results', function() {

        it('should return top results', async() => {
            chrome = await myChromeLauncher.launchChrome(true);
            chromeless = new Chromeless();

            const links = await chromeless
                .goto('https://www.google.com')
                .type('chromeless', 'input[name="q"]')
                .press(13)
                .wait('#resultStats')
                .evaluate(() => {
                    // this will be executed in headless chrome
                    const links = [].map.call(
                        document.querySelectorAll('.g h3 a'),
                        a => ({ title: a.innerText, href: a.href })
                    )
                    return links;
                });
            // Assert
            assert.equal(links.length, 11);

            await chromeless.end();

            chrome.kill().catch(e => console.error(e));
        });
    });

});

上面的测试效果很好,但是当我想使用beforebeforeEachafterafterEach方法共享如下安装代码时,出现错误:

 describe('app', function() {

     describe('Top Results', function() {
         var chrome;
         var chromeless;

         before(function() {
             chrome = await myChromeLauncher.launchChrome(true);
             chromeless = new Chromeless();
         });

 ....

         after(function() {
             await chromeless.end();
             chrome.kill().catch(e => console.error(e));
         });

});

});

错误:

chrome = await myChromeLauncher.launchChrome(true);
               ^^^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier

您的before处理程序还需要async

before(async function() {
   chrome = await myChromeLauncher.launchChrome(true);
   chromeless = new Chromeless();
});

来自文档

等待操作符用于等待Promise。 它只能在异步函数中使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM