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之前運行。請有人建議我應該如何構建這個?
如果您想在套件之前或每次測試之前運行某些內容,則可以使用before hook。 [參見摩卡文檔](https://mochajs.org/#hooks)。這些掛鉤確保了在套件/測試之前或之後由摩卡運行的東西。接下來,你不會'等待'/'使用'.then'作爲'run()'的結果,這也可能是你問題的原因。 – Rhayene
謝謝!在before hook加入之後: – ZippityUK
描述(「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