From 143181c8f26cd94ca23938cc12e5761b2321d2d0 Mon Sep 17 00:00:00 2001 From: Norman Xu Date: Fri, 10 Dec 2021 16:18:36 +0000 Subject: [PATCH] Support React Native by adding a shim for AssertionError Co-authored-by: Mark Wubben --- AssertionError.js | 1 + AssertionError.native.js | 10 ++++++++++ index.js | 2 +- package.json | 7 +++++-- test.js | 11 +++++++++++ 5 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 AssertionError.js create mode 100644 AssertionError.native.js diff --git a/AssertionError.js b/AssertionError.js new file mode 100644 index 0000000..ceedad9 --- /dev/null +++ b/AssertionError.js @@ -0,0 +1 @@ +module.exports = require('assert').AssertionError diff --git a/AssertionError.native.js b/AssertionError.native.js new file mode 100644 index 0000000..803fb49 --- /dev/null +++ b/AssertionError.native.js @@ -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 diff --git a/index.js b/index.js index eddfde0..4d92324 100644 --- a/index.js +++ b/index.js @@ -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 }) diff --git a/package.json b/package.json index 372e5a7..0935690 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,9 @@ "types": "index.d.ts", "files": [ "index.d.ts", - "index.js" + "index.js", + "AssertionError.js", + "AssertionError.native.js" ], "scripts": { "test": "standard && tsd && nyc ava" @@ -18,7 +20,8 @@ "keywords": [ "never", "typescript", - "assert" + "assert", + "react-native" ], "author": "Mark Wubben (https://novemberborn.net/)", "license": "ISC", diff --git a/test.js b/test.js index a490e6e..7aaa8fc 100644 --- a/test.js +++ b/test.js @@ -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 }) @@ -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') +})