Skip to content

Instantly share code, notes, and snippets.

@AlastairTaft
Last active April 19, 2019 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlastairTaft/66d92a27c0b2a8032867b0b13fea9f8d to your computer and use it in GitHub Desktop.
Save AlastairTaft/66d92a27c0b2a8032867b0b13fea9f8d to your computer and use it in GitHub Desktop.
Browser Test Utility
/**
* Usage
* Include this file in the <head />
*
* Then you can use HTML like so.
*
* ```html
* <browser-test pass="false">
* <span slot="description">This is a failed test</span>
* <pre slot="info">
* There was an error.
* It occured here.
* </pre>
* </browser-test>
* <browser-test pass="true">
* <span slot="description">This is a passing test</span>
* </browser-test>
*```
*
* Or you can use it in code to append test results to the dom.
* It adds a global `createNewTest` method.
*
* ```js
* var ele = createNewTest('My running test description')
* var error = new Error('test failure.') // In reality you won't create this
* ele.fail(error)
* // or
* ele.pass()
* ```
*/
class BrowserTest extends HTMLElement {
constructor() {
super();
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `<style>
.container {
position: relative;
width: 100%;
max-width: 500px;
}
.description {
width: 90%;
display: inline-block;
}
.result {
width: 9%;
display: inline-block;
}
.info {
display: block;
color: red;
}
</style>
<div class="container">
<div class="description">
<slot name="description"></slot>
</div>
<div class="result">
</div>
<div class="info">
<slot name="info"></slot>
</div>
</div>`
}
connectedCallback() {
const passed = this.getAttribute('pass') === 'true',
failed = this.getAttribute('pass') === 'false'
var resultContainer = this.shadowRoot.querySelector('.result')
if (passed)
resultContainer.innerHTML = "✅"
else if (failed)
resultContainer.innerHTML = "❌"
else
resultContainer.innerHTML = ""
}
fail(err){
this.setAttribute('pass', 'false')
this.connectedCallback()
var infoContainer = this.shadowRoot.querySelector('.info')
infoContainer.innerHTML = `<pre>
${err.stack}
</pre>`
}
pass(){
this.setAttribute('pass', 'true')
this.connectedCallback()
}
}
window.customElements.define('browser-test', BrowserTest)
/**
* Create a new BrowserTest element and append it to the document body
* @param {string} description The test description
*/
const createNewTest = function(description){
var ele = document.createElement('browser-test')
ele.innerHTML = `<span slot="description">${description}</span>`
document.body.appendChild(ele)
return ele
}
window.createNewTest = createNewTest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment