84 lines
2.5 KiB
JavaScript
84 lines
2.5 KiB
JavaScript
'use strict'
|
|
|
|
const assert = require('assert')
|
|
|
|
function deepStrictEqualInner(a, b) {
|
|
if (Object.is(a, b)) return true
|
|
if (a === null || b === null) return a === b
|
|
if (typeof a !== 'object' || typeof b !== 'object') return false
|
|
if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) return a.length === b.length && a.equals(b)
|
|
if (Buffer.isBuffer(a) || Buffer.isBuffer(b)) return false
|
|
if (Array.isArray(a)) {
|
|
if (!Array.isArray(b) || a.length !== b.length) return false
|
|
for (let i = 0; i < a.length; i++) {
|
|
if (!deepStrictEqualInner(a[i], b[i])) return false
|
|
}
|
|
return true
|
|
}
|
|
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime()
|
|
if (a instanceof RegExp && b instanceof RegExp)
|
|
return a.source === b.source && a.flags === b.flags
|
|
const keysA = Object.keys(a).sort()
|
|
const keysB = Object.keys(b).sort()
|
|
if (keysA.length !== keysB.length) return false
|
|
for (let i = 0; i < keysA.length; i++) {
|
|
if (keysA[i] !== keysB[i]) return false
|
|
}
|
|
for (const k of keysA) {
|
|
if (!deepStrictEqualInner(a[k], b[k])) return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
function patch(name, impl) {
|
|
if (typeof assert[name] !== 'function') assert[name] = impl
|
|
}
|
|
|
|
patch('deepStrictEqual', function deepStrictEqual(actual, expected, message) {
|
|
if (!deepStrictEqualInner(actual, expected)) {
|
|
assert.fail(message || 'deepStrictEqual mismatch')
|
|
}
|
|
})
|
|
|
|
patch('deepEqual', function deepEqual(actual, expected, message) {
|
|
return assert.deepStrictEqual(actual, expected, message)
|
|
})
|
|
|
|
patch('throws', function throws(fn, expected, message) {
|
|
let err
|
|
try {
|
|
fn()
|
|
} catch (e) {
|
|
err = e
|
|
}
|
|
if (err === undefined) {
|
|
assert.fail(message || 'Expected function to throw')
|
|
}
|
|
if (expected === undefined) return
|
|
if (typeof expected === 'string') {
|
|
if (!String(err.message).includes(expected)) {
|
|
assert.fail(message || `Expected message to include ${JSON.stringify(expected)}`)
|
|
}
|
|
return
|
|
}
|
|
if (expected instanceof RegExp) {
|
|
if (!expected.test(String(err.message))) {
|
|
assert.fail(message || `Expected message to match ${expected}`)
|
|
}
|
|
return
|
|
}
|
|
if (typeof expected === 'function' && expected.prototype) {
|
|
if (!(err instanceof expected)) {
|
|
assert.fail(message || `Expected ${expected.name || 'Error'}`)
|
|
}
|
|
return
|
|
}
|
|
if (typeof expected === 'function') {
|
|
if (!expected(err)) {
|
|
assert.fail(message || 'Expected validation function to return true')
|
|
}
|
|
}
|
|
})
|
|
|
|
module.exports = assert
|