izuna/test/units/dispatch.js

62 lines
1.5 KiB
JavaScript

import { it, assert, assertEq } from 'folktest'
import { dispatch } from '../../src/fantasy-land.js'
const test = (re, str = '') => re instanceof RegExp ? re.test(str) : new RegExp(re).test(str)
const assertErr = (f, err) => {
try {
f()
} catch (e) {
if (typeof err === 'string' || err instanceof RegExp) {
assert(test(err, e.message), `${err} did not match ${e.message}`)
} else if (typeof err === 'function') {
assert(e.constructor === err)
}
return
}
const expected = err ? `"${err}" ` : ""
assert(false, `expecting error ${expected}but function did not throw`)
}
const wrong = msg => assert(false, msg)
export const Dispatch = [
it('should dispatch to any listed method or fallback', () => {
const a1 = {
['fantasy-land/test']: x => assertEq(x, 1),
test: () => wrong(`a1['test'] should not have been called`)
}
const f1 = dispatch(['fantasy-land/test', 'test'], (v, x) => {
wrong(`f1 fallback should not have been called for ${JSON.stringify(x)}`)
})
f1(1, a1)
delete a1['fantasy-land/test']
assertErr(() => {
f1(1, a1)
})
const f2 = dispatch(['test', 'fantasy-land/test'], (v, x) => {
wrong(`f2 fallback should not have been called for ${JSON.stringify(x)}`)
})
const a2 = {
['fantasy-land/test']: () => wrong(`a2['fantasy-land/test'] should not have been called`),
test: x => assertEq(x, 2)
}
f2(2, a2)
const f3 = dispatch(['fantasy-land/test', 'test'], x => {
assertEq(x, 3)
})
f3(3, {})
})
]