assert.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function eq(actual, expected, msg) {
  2. if (actual !== expected) {
  3. throw new Error(`${msg || 'eq'}: expected ${JSON.stringify(expected)} got ${JSON.stringify(actual)}`);
  4. }
  5. }
  6. function ok(value, msg) {
  7. if (!value) throw new Error(`${msg || 'ok'}: expected truthy, got ${JSON.stringify(value)}`);
  8. }
  9. function notOk(value, msg) {
  10. if (value) throw new Error(`${msg || 'notOk'}: expected falsy, got ${JSON.stringify(value)}`);
  11. }
  12. function deepEq(actual, expected, msg) {
  13. const a = JSON.stringify(actual);
  14. const b = JSON.stringify(expected);
  15. if (a !== b) throw new Error(`${msg || 'deepEq'}: expected ${b} got ${a}`);
  16. }
  17. function arrEq(actual, expected, msg) {
  18. if (!Array.isArray(actual) || !Array.isArray(expected)) throw new Error(`${msg || 'arrEq'}: not arrays`);
  19. if (actual.length !== expected.length) throw new Error(`${msg || 'arrEq'}: length ${actual.length} !== ${expected.length}`);
  20. for (let i = 0; i < expected.length; i++) {
  21. if (actual[i] !== expected[i]) throw new Error(`${msg || 'arrEq'}: at ${i} expected ${expected[i]} got ${actual[i]}`);
  22. }
  23. }
  24. async function throwsAsync(fn, msgMatch) {
  25. try {
  26. await fn();
  27. } catch (e) {
  28. if (msgMatch instanceof RegExp) {
  29. if (!msgMatch.test(e.message)) throw new Error(`throwsAsync: expected ${msgMatch} to match, got "${e.message}"`);
  30. } else if (msgMatch && !String(e.message).includes(msgMatch)) {
  31. throw new Error(`throwsAsync: expected "${msgMatch}" in error, got "${e.message}"`);
  32. }
  33. return e;
  34. }
  35. throw new Error(`throwsAsync: expected throw${msgMatch ? ' with ' + msgMatch : ''}, none thrown`);
  36. }
  37. module.exports = { eq, ok, notOk, deepEq, arrEq, throwsAsync };