A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Console.assert and AssertionError

Jxck
2015-05-27

more for console.assert

console.assert on browser doesn’t throw AssertionError, only display message to dev-console. and AssertionError in browser doesn’t expose from browser. I think these are not useful as standard API.

assertion for test

assertion for testing could build upon console.assert if that throws AssertionError.

class MyAssertionForTest {
  equals(act, exp, msg) {
    console.assert(act === exp, msg);
  }
}

and if AssertionError exposed for public, we can do throw new AssertionError('my own') or extend it by owerself. node.js has own AssertionError in assert module, but buildin is better to getting platform suppor.

asserting condition

assertion API is not only for testing, but use for checking pre/post/invariant condition.

function login(name, pass) {
  // pre-condition
  console.assert(typeof name === 'string', 'name should be string');
  console.assert(typeof pass === 'string', 'pass should be string');

  // login logic
}

but in browser, it’s only shows message to dev-console. there is no way to handle that in JS code, depends on only human eyes.

wrap up

  • expose AssertionError
  • console.assert should throw AssertionError not only display message.

if it’s not part of console.assert, it’s fine to consider native assert() for JavaScript instead.