← back to AbramsOS

tests/ids.test.js

41 lines

// ULID-prefix ID helper tests.

const test = require('node:test');
const assert = require('node:assert');
const { id } = require('../lib/ids');

test('returns prefix_<lowercase-ulid>', () => {
  const x = id('user');
  assert.match(x, /^user_[0-9a-z]{26}$/, `got: ${x}`);
});

test('all known kinds emit a recognized prefix', () => {
  for (const kind of ['user', 'consent', 'connector', 'source', 'document', 'purchase', 'item']) {
    const x = id(kind);
    assert.match(x, /^[a-z]+_[0-9a-z]{26}$/);
  }
});

test('throws on unknown kind', () => {
  assert.throws(() => id('totally-bogus'), /Unknown id kind/);
});

test('two consecutive ids are distinct', () => {
  const a = id('purchase');
  const b = id('purchase');
  assert.notStrictEqual(a, b);
});

test('ULIDs are sortable lexicographically (monotonic over time)', async () => {
  const a = id('purchase');
  await new Promise((r) => setTimeout(r, 5));
  const b = id('purchase');
  // ULID timestamps mean later id should be >= earlier when compared as strings
  assert.ok(a.localeCompare(b) <= 0, `expected ${a} <= ${b}`);
});

test('id strings are lowercase (db convention)', () => {
  const x = id('document');
  assert.strictEqual(x, x.toLowerCase());
});