Taken from
Puppeteer GitHub:
Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol.
 |
Puppeteer |
Install puppeteer as a dev dependency if you use it only during development.
npm i --save-dev puppeteer
yarn add -dev puppeteer
Example
How to use puppeteer together with mocha to write JavaScript, HTML and CSS tests?
Let's say this is my HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Puppet</title>
<script type="text/javascript" src="./build/amazingService.bundle.js"></script>
</head>
<body>
<p onClick=“beAmazed()”>Amazing Service</p>
<script>
function beAmazed() {
const amazingService = new AmazingService();
amazingService.getAmazing().then(res => console.log(res));
}
</script>
</body>
</html>
To test document.querySelectorAll
page.$$eval(selector, pageFunction[, ...args])
To test document.querySelector
page.$eval(selector, pageFunction[, ...args])
To test whether a script is imported to a page as expected
page.evaluate(pageFunction, ...args)
Mocha and Puppeteer Tests
1) Serve your index.html over localhost using
http-server or python -m SimpleHTTPServer.
2) Run npm test (which runs mocha)
describe(('test Amazing Service'), () => {
let browser;
const puppeteerOpts = {
headless: true,
slowMo: 100,
timeout: 5000,
};
before(async () => {
browser = await puppeteer.launch(puppeteerOpts);
});
after(async () => {
await browser.close();
});
it('should be amazing', async () => {
const page = await browser.newPage();
await page.goto('http://localhost:8000');
expect(await page.title()).to.equal('My Puppet');
const divsCounts = await page.$$eval('div', divs => divs.length);
expect(divsCounts).to.equal(0);
// the following syntax is needed if you use babel as of March 5th 2018
const response = await page.evaluate(`(async () => {
const amazingService = new AmazingService();
const rate = await amazingService.getAmazing();
return Promise.resolve({ rate });
})()`);
expect(response).to.have.property('rate');
expect(response.rate).to.equal(100);
}).timeout('5s');
});
There are many other functions of puppeteer. Please check out Google Chrome
Puppeteer examples and
Puppeteer API document to learn more about Puppeteer.
Thanks for reading!
Jun
Comments
Post a Comment