0

我面临一个关于测试设置和清理before以及测试after方法的问题Mocha

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

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

简单的.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));
        });
    });

});

上面的测试运行良好,但是当我想使用before、或方法来共享设置代码时beforeEach,如下所示,我得到一个错误:afterafterEach

 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
4

1 回答 1

4

你的before处理程序也需要是asyncie

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

文档

await 运算符用于等待 Promise。它只能在异步函数中使用。

于 2017-08-08T09:54:25.133 回答