Skip to content

How to test ECMAScript modules in the browser

Lloyd Brookes edited this page Dec 12, 2019 · 2 revisions

Install web-runner.

$ npm install --save-dev @test-runner/web

Typical web test file example.

import Tom from 'test-object-model'
import 'https://www.chaijs.com/chai.js'

const assert = chai.assert
const tom = new Tom()

tom.test('Math.random() should return a number between 0 and 1', function () {
  const result = Math.random()
  assert.equal(typeof result, 'number')
  assert.ok(result >= 0 && result <= 1)
})

tom.test('REST API should return the current todo item', async function () {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  const todo = await response.json()
  assert.equal(todo.userId, 1)
  assert.equal(todo.title, 'delectus aut autem')
})

export default tom

Run the tests using web-runner. This runner is identical to test-runner with the one difference that it runs the tests in Chromium rather than Node.js.

$ npx web-runner test.mjs

Start: 2 tests loaded

✓ synopsis Math.random() should return a number between 0 and 1
✓ synopsis REST API should return the current todo item

Completed in 199ms. Pass: 2, fail: 0, skip: 0.