Skip to content

Commit

Permalink
added tests, launch settings, package.json
Browse files Browse the repository at this point in the history
Signed-off-by: Silvan Strübi <[email protected]>
  • Loading branch information
Silvan Strübi committed Jun 5, 2020
1 parent f539afd commit 16a2f4b
Show file tree
Hide file tree
Showing 9 changed files with 612 additions and 0 deletions.
43 changes: 43 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.0.1-beta",
"configurations": [
{
"name": "Launch Source",
"type": "firefox",
"request": "launch",
"reAttach": false,
"reloadOnChange": {
"watch": ["${workspaceFolder}/src/**/*.js", "${workspaceFolder}/**/*.html"],
"ignore": "**/node_modules/**"
},
"internalConsoleOptions": "openOnSessionStart",
"firefoxArgs": ["-devtools"],
"url": "${workspaceFolder}/index.html",
"webRoot": "${workspaceFolder}/src"
},
{
"name": "Launch Test",
"type": "firefox",
"request": "launch",
"reAttach": false,
"reloadOnChange": {
"watch": ["${workspaceFolder}/test/**/*.js", "${workspaceFolder}/test/**/*.html"],
"ignore": "**/node_modules/**"
},
"internalConsoleOptions": "openOnSessionStart",
"url": "${workspaceFolder}/test/index.html",
"webRoot": "${workspaceFolder}/test"
},
{
"name": "Launch TestChrome",
"type": "chrome",
"request": "launch",
"internalConsoleOptions": "openOnSessionStart",
"url": "http://localhost/${workspaceFolder}/test/index.html",
"webRoot": "${workspaceFolder}/test"
}
]
}
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"cSpell.words": [
],
"editor.tabSize": 2,
"editor.detectIndentation": false
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Silvan Strübi

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
14 changes: 14 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "event-driven-web-components-realworld-example-app",
"version": "0.0.1-beta",
"description": "Exemplary real world application built with Vanilla JS Web Components in an Event Driven Architecture",
"main": "./src/index.html",
"scripts": {
"test": "standard --fix"
},
"author": "[email protected]",
"license": "MIT",
"devDependencies": {
"standard": "^14.3.3"
}
}
157 changes: 157 additions & 0 deletions test/es/Test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// @ts-check

/* global customElements */
/* global self */

export default class Test {
/**
* Creates an instance of Test
* @param {string} name
* @param {string} [namespace = ''] // is very important if the same test runs more than once in the same session
* @memberof Test
*/
constructor (name, namespace = '') {
this.namespace = namespace

this.summaries = document.createElement('div')
this.summaries.innerHTML = `<a href=#${name}>${name} had <span class=hasDone></span> test runs done from which <span class=hasPassed></span> passed and <span class=hasFailed></span> failed</a>`
document.getElementById('summary').appendChild(this.summaries)
this.summarySpaceDone = this.summaries.getElementsByClassName('hasDone')[0]
this.summarySpacePassed = this.summaries.getElementsByClassName('hasPassed')[0]
this.summarySpaceFailed = this.summaries.getElementsByClassName('hasFailed')[0]
this.counter = 0
this.passedCounter = 0
this.failedCounter = 0

const results = document.createElement('div')
results.innerHTML = `
<div>
<a name=${name}></a>
<h2>Results: ${name}</h2>
<div class=result></div>
</div>
<div>
<h2>Test Artifacts</h2>
<div class=test></div>
</div>
`
document.getElementById('results').appendChild(results)
document.getElementById('results').appendChild(document.createElement('hr'))
this.resultSpace = results.getElementsByClassName('result')[0]
this.testSpace = results.getElementsByClassName('test')[0]

self.onerror = (message, source, lineno, colno, error) => {
const errorEl = document.createElement('div')
errorEl.classList.add(errorEl.textContent = 'failed')
errorEl.textContent += `message: ${message}, source: ${source}, lineno: ${lineno}, colno: ${colno}, error: ${error}}`
this.summaries.appendChild(errorEl)
}
}

/**
* runs a web-component test by first importing the needed module, define it and test it
*
* @param {string} testName
* @param {string} [moduleName='default']
* @param {string} modulePath
* @param {(HTMLElement)=>boolean} testFunction
* @param {string} [attributes='']
* @param {(Function)=>Function} [extendsFunction=(Function)=>Function]
* @memberof Test
* @return {Promise<Element>}
*/
runTest (testName, moduleName = 'default', modulePath, testFunction, attributes = '', extendsFunction = func => func) {
testName = this.namespace ? `${testName}-${this.namespace}` : testName
return import(modulePath).then(module => {
// test shadowRoot
try {
if (!customElements.get(testName)) customElements.define(testName, extendsFunction(!module[moduleName].toString().includes('=>') ? class extends module[moduleName] {} : module[moduleName]()))
} catch (error) {
console.error(`Note! testName: ${testName} must be lower case with hyphen separated!`, error)
}
return this.test(testName, testFunction, attributes, null)
})
}

/**
* test a web-component
*
* @param {string} testName
* @param {(HTMLElement)=>boolean} testFunction
* @param {string} [attributes='']
* @param {Element} [testEl = null]
* @param {boolean} hidden
* @return {Element | null}
*/
test (testName, testFunction, attributes = '', testEl = null, hidden = false) {
if (!testEl) {
const container = document.createElement('div')
container.innerHTML = `<${testName} ${attributes}>&lt;${testName}&gt;</${testName}>`
testEl = container.getElementsByTagName(testName)[0]
this.testSpace.appendChild(testEl)
// @ts-ignore
testEl.hidden = hidden
} else {
const placeHolder = document.createElement('div')
placeHolder.textContent = `reused: <${testEl.tagName.toLowerCase()}> for ${testName} test`
placeHolder.classList.add('placeHolder')
this.testSpace.appendChild(placeHolder)
placeHolder.hidden = hidden
}
if (testEl) {
const resultEl = document.createElement('div')
if (testFunction(testEl)) {
resultEl.classList.add(resultEl.textContent = 'passed')
if (!hidden) this.passedCounter++
} else {
resultEl.classList.add(resultEl.textContent = 'failed')
if (!hidden) this.failedCounter++
}
testEl.className = ''
testEl.classList.add(resultEl.textContent)
resultEl.textContent += `: ${testName.replace(`-${this.namespace}`, '')}`
this.resultSpace.appendChild(resultEl)
resultEl.hidden = hidden
if (hidden) console.info(`${testFunction(testEl) ? 'passed' : 'failed'} hidden test: ${testName} on element: ${testEl.tagName.toLowerCase()}`)
}
if (!hidden) this.counter++
this.updateSummary()
return testEl
}

updateSummary () {
if (Number(this.summarySpaceFailed.textContent) > 0) this.summaries.classList.add('failed')
if (Number(this.summarySpacePassed.textContent) === Number(this.summarySpaceDone.textContent)) {
this.summaries.classList.add('passed')
} else {
this.summaries.classList.remove('passed')
}
}

set counter (number) {
this._counter = number
this.summarySpaceDone.textContent = number
}

get counter () {
return this._counter
}

set passedCounter (number) {
this._passedCounter = number
this.summarySpacePassed.textContent = number
}

get passedCounter () {
return this._passedCounter
}

set failedCounter (number) {
this._failedCounter = number
this.summarySpaceFailed.textContent = number
}

get failedCounter () {
return this._failedCounter
}
}
52 changes: 52 additions & 0 deletions test/es/tests/components/prototypes/MasterIntersectionObserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// @ts-nocheck

/* global CustomEvent */
/* global self */

import Test from '../../../Test.js'

let counter = 0

/**
* MasterIntersectionObserver Tests
*
* @param {string} testTitle
* @param {string} moduleName
* @param {string} modulePath
* @param {string} [namespace = '']
*/
export const test = (testTitle = 'MasterIntersectionObserver', moduleName = 'MasterIntersectionObserver', modulePath = '../../src/es/components/prototypes/MasterIntersectionObserver.js', namespace = counter) => {
// test modulePath must be from Test.js perspective
const test = new Test(testTitle, namespace)

// INTERSECTION -----------------------------------------------------------------------------------------------
let eventDispatched = false
let eventReceived = false
test.runTest('intersection-observer-setup', moduleName, modulePath,
el => el,
undefined,
(subclass) => class extends subclass {
constructor (masterArgs = {}, ...args) {
super(Object.assign(masterArgs, { intersectionObserverInit: {} }), ...args)
this.css = `this{
position: absolute;
top: 2000px;
}`
}
}
).then(el => {
document.body.addEventListener('HelloFromComponent', event => (eventDispatched = true))
el.addCustomEventListener(document.body, 'HelloFromBody', event => (eventReceived = true))
el.dispatchCustomEvent(el.getCustomEvent('HelloFromComponent'))
document.body.dispatchEvent(new CustomEvent('HelloFromBody', { bubbles: true, cancelable: true, detail: null, composed: true }))
test.test('intersection-observer-not-dispatched-nor-received', el => !eventDispatched && !eventReceived, undefined, el)
self.scrollTo(0, document.body.scrollHeight + 200)
setTimeout(() => {
test.test('intersection-observer-dispatched-received', el => eventDispatched && eventReceived, undefined, el)
el.css = ''
self.scrollTo(0, 0)
}, 50)
})
// ------------------------------------------------------------------------------------------------------------
counter++
}
86 changes: 86 additions & 0 deletions test/es/tests/components/prototypes/MasterMutationObserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// @ts-nocheck

import Test from '../../../Test.js'

let counter = 0

/**
* MasterMutationObserver Tests
*
* @param {string} testTitle
* @param {string} moduleName
* @param {string} modulePath
* @param {string} [namespace = '']
*/
export const test = (testTitle = 'MasterMutationObserver', moduleName = 'MasterMutationObserver', modulePath = '../../src/es/components/prototypes/MasterMutationObserver.js', namespace = counter) => {
// test modulePath must be from Test.js perspective
const test = new Test(testTitle, namespace)

// MUTATION------------------------------------------------------------------------------------------------------
let gotAttributeMutation = false
let gotChildListMutation = false
test.runTest('mutation-observer-by-attribute-setup', moduleName, modulePath,
el => el,
`mutationObserverInit="{
'attributes': true,
'characterData': true,
'childList': true
}"`,
(subclass) => class extends subclass {
constructor (masterArgs = {}, ...args) {
super(masterArgs, ...args)
}

connectedCallback () {
super.connectedCallback()
this.setAttribute('hello', 'world')
this.root.appendChild(document.createElement('span'))
}

mutationCallback (mutationList, observer) {
super.mutationCallback(mutationList, observer)
mutationList.forEach(mutation => {
if (mutation.type === 'attributes' && mutation.attributeName === 'hello') gotAttributeMutation = true
if (mutation.type === 'childList') gotChildListMutation = true
})
}
}
).then(el => {
test.test('mutation-observer-by-attribute', el => gotAttributeMutation && gotChildListMutation, undefined, el)
})
let gotAttributeMutation2 = false
let gotChildListMutation2 = false
test.runTest('mutation-observer-by-extends-setup', moduleName, modulePath,
el => el,
undefined,
(subclass) => class extends subclass {
constructor (masterArgs = {}, ...args) {
super(Object.assign(masterArgs, {
mutationObserverInit: {
attributes: true,
characterData: true,
childList: true
}
}), ...args)
}

connectedCallback () {
super.connectedCallback()
this.setAttribute('hello', 'world')
this.root.appendChild(document.createElement('span'))
}

mutationCallback (mutationList, observer) {
super.mutationCallback(mutationList, observer)
mutationList.forEach(mutation => {
if (mutation.type === 'attributes' && mutation.attributeName === 'hello') gotAttributeMutation2 = true
if (mutation.type === 'childList') gotChildListMutation2 = true
})
}
}
).then(el => {
test.test('mutation-observer-by-extends', el => gotAttributeMutation2 && gotChildListMutation2, undefined, el)
})
// ------------------------------------------------------------------------------------------------------------
counter++
}
Loading

0 comments on commit 16a2f4b

Please sign in to comment.