Skip to content

Commit

Permalink
Support React Native by adding a shim for AssertionError
Browse files Browse the repository at this point in the history
Co-authored-by: Mark Wubben <[email protected]>
  • Loading branch information
normanzb and novemberborn authored Dec 10, 2021
1 parent f5da817 commit 143181c
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 3 deletions.
1 change: 1 addition & 0 deletions AssertionError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require('assert').AssertionError
10 changes: 10 additions & 0 deletions AssertionError.native.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Enable use in React Native by shimming the Node.js AssertionError.

class AssertionError extends Error {
constructor ({ message }) {
super(message)
this.name = 'AssertionError'
}
}

module.exports = AssertionError
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict'
const { AssertionError } = require('assert')
const AssertionError = require('./AssertionError')

function never (message = 'Unexpected call to never()') {
throw new AssertionError({ message, stackStartFn: never })
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@
"types": "index.d.ts",
"files": [
"index.d.ts",
"index.js"
"index.js",
"AssertionError.js",
"AssertionError.native.js"
],
"scripts": {
"test": "standard && tsd && nyc ava"
},
"keywords": [
"never",
"typescript",
"assert"
"assert",
"react-native"
],
"author": "Mark Wubben (https://novemberborn.net/)",
"license": "ISC",
Expand Down
11 changes: 11 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const { AssertionError } = require('assert')
const test = require('ava')
const never = require('.')
const ShimmedAssertionError = require('./AssertionError.native')

test('throws when called', t => {
t.throws(never, { instanceOf: AssertionError })
Expand All @@ -22,3 +23,13 @@ test('never() is not in the error stack', t => {
const error = t.throws(wrapper)
t.regex(error.stack.split('\n')[1], /wrapper/)
})

test('the shimmed AssertionError can be constructed', t => {
const error = t.throws(() => {
throw new ShimmedAssertionError({ message: 'Error message' })
}, {
instanceOf: ShimmedAssertionError,
message: 'Error message'
})
t.is(error.name, 'AssertionError')
})

0 comments on commit 143181c

Please sign in to comment.