2017-10-06 70 views
0

JavaScript新手,並試圖瞭解如何運行以下簡單測試,其中加載谷歌主頁,並獲得標題。然後測試此標題。Google Puppeteer和Mocha異步調用

const puppeteer = require("puppeteer"); 
var page_title = "blank"; 
assert = require("assert"); 

async function run() { 
    const browser = await puppeteer.launch({ headless: true }); 
    const page = await browser.newPage(); 
    await page.goto("http://www.google.co.uk"); 
    page_title = await page.title(); 
    console.log("Page Title: ", page_title) 
    await browser.close(); 
} 

run(); 

describe("Google", function() { 
    it("Title contains Google", async function() { 
    assert.equal(page_title, "Google"); 
    }); 
}); 

問題是describe/it塊在獲得page_title之前運行。請有人建議我應該如何構建這個?

+0

如果您想在套件之前或每次測試之前運行某些內容,則可以使用before hook。 [參見摩卡文檔](https://mochajs.org/#hooks)。這些掛鉤確保了在套件/測試之前或之後由摩卡運行的東西。接下來,你不會'等待'/'使用'.then'作爲'run()'的結果,這也可能是你問題的原因。 – Rhayene

+0

謝謝!在before hook加入之後: – ZippityUK

+0

描述(「Google」,function(){async function(){this.timeout(10000); const browser {await puppeteer.launch({headless:true}); (); const page = await browser.newPage(); await page.goto(「http://www.google.co.uk」); page_title =等待page.title(); //console.log(「頁面標題:」 PAGE_TITLE) 伺機browser.close(); }); 它( 「標題包含谷歌」,函數(){ assert.equal(PAGE_TITLE, 「谷歌」); }); }); – ZippityUK

回答

0

您只需要閱讀摩卡documentation。無需深入挖掘,async code位於TOC

摩卡提供3種方式:

  • 回調

    當你的測試完整只需調用回調。通過向它()添加回調(通常名爲完成)。

  • 承諾
  • asyncawait

因此,修訂後的像這樣與asyncawait

const puppeteer = require("puppeteer"); 
var page_title = "blank"; 
assert = require("assert"); 

describe("Google", function() { 
    // this.timeout(0); 
    it("Title contains Google", async()=> { 
     const browser = await puppeteer.launch(); //headless by default 
     const page = await browser.newPage(); 
     await page.goto("http://www.google.co.uk"); 
     page_title = await page.title(); 
     console.log("Page Title: ", page_title); 
     assert.equal(page_title, "Google"); 
     await browser.close() 
    }); 
}); 

我的建議是對TOC每一個解釋快速閱讀,讀brief explanation async and await