2017-08-08 53 views
0

我面臨的問題有關測試設置和清理和after方法Mocha測試。與之前在摩卡範圍內的問題

我使用Chromeless進行端到端測試。對於更容易實現我提出我的Chrome啓動一個單獨的文件(比如說my-chrome-launcher.js)通過導出async功能:

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

}); 

以上測試效果很好,但是當我想要使用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

before處理程序也需要async

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

docs

The await operator is used to wait for a Promise. It can only be used inside an async function.