Skip to content

Commit

Permalink
feature: Implement custom JS helper import
Browse files Browse the repository at this point in the history
  • Loading branch information
fabschurt committed May 6, 2024
1 parent 1a9f810 commit 0545073
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/domain/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const HELPER_FILE_PATH = 'helpers.mjs'

export const importCustomHelpers = (withSrcDir, ifPathExists) => (
withSrcDir((prefixWithSrcDir) => (
ifPathExists(
prefixWithSrcDir(HELPER_FILE_PATH),
(filePath) => import(filePath),
{},
)
))
)
32 changes: 32 additions & 0 deletions tests/domain/helpers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, it } from 'node:test'
import assert from 'node:assert'
import { withTempDir } from '#tests/helpers'
import * as fs from 'node:fs/promises'
import { join } from 'node:path'
import { withDir, ifPathExists } from '#src/utils/fs'
import { importCustomHelpers } from '#src/domain/helpers'

describe('#src/domain/helpers', () => {
describe('importCustomHelpers()', () => {
it('parses exports from a `helpers.js` file', async () => {
await withTempDir(async (prefixWithTempDir) => {
const srcDirPath = prefixWithTempDir('src')
const filePath = join(srcDirPath, 'helpers.mjs')

await fs.mkdir(srcDirPath)
await fs.writeFile(filePath, `
export const sayHello = () => 'Hello World!'
export const add2 = (num) => num + 2
`)

const helpers = await importCustomHelpers(withDir(srcDirPath), ifPathExists)

assert('sayHello' in helpers)
assert('add2' in helpers)
assert.strictEqual(helpers.sayHello(), 'Hello World!')
assert.strictEqual(helpers.add2(4), 6)
})
})
})
})

0 comments on commit 0545073

Please sign in to comment.