api-api-merge.test.mjs 2.15 KB
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { parse } from '@babel/parser'
import { describe, it } from 'node:test'

const testDir = path.dirname(fileURLToPath(import.meta.url))
const projectRoot = path.resolve(testDir, '../..')

async function readApiSource() {
  return readFile(path.join(projectRoot, 'api/api.js'), 'utf8')
}

function getExportedMethodNames(source) {
  const ast = parse(source, { sourceType: 'module' })
  const assignment = ast.program.body.find(
    node =>
      node.type === 'ExpressionStatement' &&
      node.expression.type === 'AssignmentExpression' &&
      node.expression.left.type === 'MemberExpression' &&
      node.expression.left.object.type === 'Identifier' &&
      node.expression.left.object.name === 'module' &&
      node.expression.left.property.type === 'Identifier' &&
      node.expression.left.property.name === 'exports'
  )

  assert.ok(assignment, 'api/api.js should assign its API object to module.exports')
  assert.equal(assignment.expression.right.type, 'ObjectExpression')

  return assignment.expression.right.properties
    .filter(node => node.type === 'ObjectMethod')
    .map(node => node.key.name || node.key.value)
}

describe('api/api.js merge resolution', () => {
  it('contains no merge markers and parses as JavaScript', async () => {
    const source = await readApiSource()
    assert.doesNotMatch(source, /^(?:<<<<<<<|=======|>>>>>>>)/m)
    assert.doesNotThrow(() => parse(source, { sourceType: 'module' }))
  })

  it('exports every branch-only API once', async () => {
    const methodNames = getExportedMethodNames(await readApiSource())
    const duplicates = methodNames.filter(
      (name, index) => methodNames.indexOf(name) !== index
    )

    assert.deepEqual(duplicates, [])
    assert.deepEqual(
      [
        'getShopWithYqList',
        'getOrderWaitForAudit',
        'getDemandStoreListAPI',
        'getStaffDictListAPI',
        'addStaffDictListAPI',
        'getRecruitmentPageAPI',
        'getAllStaffListAPI'
      ].filter(name => !methodNames.includes(name)),
      []
    )
  })
})