Skip to content

Instantly share code, notes, and snippets.

@soldair
Last active February 23, 2018 21:46
Show Gist options
  • Save soldair/b48a0022dbef999f241881f80d7575a9 to your computer and use it in GitHub Desktop.
Save soldair/b48a0022dbef999f241881f80d7575a9 to your computer and use it in GitHub Desktop.
coverage doesn't include service worker js reduced test case
{
"name": "pupeteer-service-worker-coverage-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"bin": {
"b48a0022dbef999f241881f80d7575a9": "./service-worker-test.js"
},
"author": "Ryan Day",
"license": "MIT",
"bugs": {
"url": ""
},
"homepage": "",
"dependencies": {
"puppeteer": "^1.1.0"
}
}
#!/usr/bin/env node
'use strict'
//"puppeteer": "^1.1.0",
const puppeteer = require('puppeteer')
const http = require('http')
// browser js to register service worker.
const setupjs = `
navigator.serviceWorker.register('/worker',{scope:"/"}).then((reg)=>{
window.swinstalled = true
console.log('install successful')
}).catch((e)=>{
window.swinstalled = false
console.log('install failed.',e)
})
`
// the actual service worker.
const worker = `
self.addEventListener('install', function(event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
event.respondWith(new Response("response from worker!", {headers: {'Content-Type': 'application/json'}}))
})
`
// create an http server to serve index and the worker.
var server = http.createServer(function (req, res) {
if (req.url === '/worker') {
res.setHeader('content-type', 'application/javascript')
return res.end(worker)
}
res.setHeader('content-type', 'text/html')
res.end('index <script>' + setupjs + '</script>')
})
server.listen(0, async function (err) {
if (err) throw err
const address = 'http://localhost:' + this.address().port
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.coverage.startJSCoverage()
await page.goto(address)
// wait for sw to be installed
await page.waitForFunction('window.swinstalled !== undefined')
const res = await makeRequest(page, '/should-hit-worker')
console.log(res.body === 'response from worker!', 'should be response from service worker.')
const coverage = await page.coverage.stopJSCoverage()
console.log('=== coverage ===')
console.log(JSON.stringify(coverage, null, ' '))
await browser.close()
server.unref()
})
//
// wrap up the fetch api so its easier to call through puppeteer
async function makeRequest (page, path) {
var id = Date.now() + '' + Math.random()
await page.evaluate(`
fetch(${JSON.stringify(path || '')}).then((res)=>{
var method = res.method
var status = res.statusCode
var headers = [...res.headers]
res.text().then((body)=>{
window["${id}"] = [null,{method,status,headers,body}]
}).catch((e)=>{
window["${id}"] = [e+'']
})
}).catch((e)=>{
window["${id}"] = [e+'']
})
`)
await page.waitForFunction(`window["${id}"] !== undefined`)
var res = await page.evaluate(`JSON.stringify(window["${id}"])`)
res = JSON.parse(res)
if (res[0]) throw new Error(res[0])
return res[1]
}
process.on('unhandledRejection', e => { console.log(e); process.exit(1) })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment