1
0
Fork 0
Browse Source

feat: add new module to reference DOM elements

Signed-off-by: André Jaenisch <andre.jaenisch@posteo.de>
combat-scorched-earth-from-outer-space
André Jaenisch 9 months ago
parent
commit
9b66e3466f
Signed by: ryuno-ki
GPG Key ID: 5A668E771F1ED854
  1. 1
      .mocharc.cjs
  2. 53
      src/js/dom.js
  3. 11
      test/fake-browser.js
  4. 38
      test/js/dom.test.js
  5. 5
      types/dom.d.ts

1
.mocharc.cjs

@ -4,4 +4,5 @@ module.exports = {
color: true,
recursive: true,
reporter: 'tap',
require: ['./test/fake-browser.js']
}

53
src/js/dom.js

@ -0,0 +1,53 @@
export const dom = {
canvas: getCanvas(),
xinput: getXInput(),
yinput: getYInput()
}
/**
* Queries the DOM for a reference to the canvas element.
*
* @returns {HTMLCanvasElement}
* @throws {Error}
*/
function getCanvas () {
const canvas = document.getElementById('game')
if (!canvas) {
throw new Error('Canvas element not found!')
}
return /** @type {HTMLCanvasElement} */(canvas)
}
/**
* Queries the DOM for a reference to the xinput element.
*
* @returns {HTMLInputElement}
* @throws {Error}
*/
function getXInput () {
const xinput = document.getElementById('xgravity')
if (!xinput) {
throw new Error('Input element xgravity not found!')
}
return /** @type {HTMLInputElement} */(xinput)
}
/**
* Queries the DOM for a reference to the yinput element.
*
* @returns {HTMLInputElement}
* @throws {Error}
*/
function getYInput () {
const yinput = document.getElementById('ygravity')
if (!yinput) {
throw new Error('Input element ygravity not found!')
}
return /** @type {HTMLInputElement} */(yinput)
}

11
test/fake-browser.js

@ -0,0 +1,11 @@
// This file is to executed by mocha before the tests are run
global.document = {
createElement: function () {},
getElementById: function (id) {
// TODO: Decide according to `id` which fake element to return
return {
id
}
}
}

38
test/js/dom.test.js

@ -0,0 +1,38 @@
import { expect } from 'chai'
import { dom } from '../../src/js/dom.js'
describe('DOM', function () {
it('should get a reference to the canvas element', function () {
// Arrange
/* Nothing to do */
// Act
const { canvas } = dom
// Assert
expect(canvas).not.to.be.undefined
})
it('should get a reference to the xinput element', function () {
// Arrange
/* Nothing to do */
// Act
const { xinput } = dom
// Assert
expect(xinput).not.to.be.undefined
})
it('should get a reference to the yinput element', function () {
// Arrange
/* Nothing to do */
// Act
const { yinput } = dom
// Assert
expect(yinput).not.to.be.undefined
})
})

5
types/dom.d.ts vendored

@ -0,0 +1,5 @@
export namespace dom {
const canvas: HTMLCanvasElement;
const xinput: HTMLInputElement;
const yinput: HTMLInputElement;
}
Loading…
Cancel
Save