From 73caeac0fba13f83a810eab27dbc0aa49b3e9ef3 Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 26 Jun 2021 17:05:59 -0400 Subject: [PATCH] Test updates (#1763) * Allow passing of globals to custom VMs * Add _serializeError * Expose document to VM --- dev/database-vm.js | 6 +++--- dev/translator-vm.js | 4 ++-- test/test-anki-note-builder.js | 25 ++++++++++++++++++++++++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/dev/database-vm.js b/dev/database-vm.js index b682bca3..014c989f 100644 --- a/dev/database-vm.js +++ b/dev/database-vm.js @@ -101,8 +101,8 @@ function atob(data) { } class DatabaseVM extends VM { - constructor() { - super({ + constructor(globals={}) { + super(Object.assign({ chrome, Image, Blob, @@ -111,7 +111,7 @@ class DatabaseVM extends VM { IDBKeyRange: global.IDBKeyRange, JSZip, atob - }); + }, globals)); this.context.window = this.context; this.indexedDB = global.indexedDB; } diff --git a/dev/translator-vm.js b/dev/translator-vm.js index f68b25db..7eab47b8 100644 --- a/dev/translator-vm.js +++ b/dev/translator-vm.js @@ -26,8 +26,8 @@ function clone(value) { } class TranslatorVM extends DatabaseVM { - constructor() { - super(); + constructor(globals) { + super(globals); this._japaneseUtil = null; this._translator = null; this._ankiNoteDataCreator = null; diff --git a/test/test-anki-note-builder.js b/test/test-anki-note-builder.js index aad12aba..d3ea0b6a 100644 --- a/test/test-anki-note-builder.js +++ b/test/test-anki-note-builder.js @@ -18,6 +18,7 @@ const fs = require('fs'); const path = require('path'); const assert = require('assert'); +const {JSDOM} = require('jsdom'); const {testMain} = require('../dev/util'); const {TranslatorVM} = require('../dev/translator-vm'); @@ -27,7 +28,10 @@ function clone(value) { } async function createVM() { - const vm = new TranslatorVM(); + const dom = new JSDOM(); + const {document} = dom.window; + + const vm = new TranslatorVM({document}); const dictionaryDirectory = path.join(__dirname, 'data', 'dictionaries', 'valid-dictionary1'); await vm.prepare(dictionaryDirectory, 'Test Dictionary 2'); @@ -68,6 +72,25 @@ async function createVM() { return this._serializeMulti(this._templateRenderer.renderMulti(items)); } + _serializeError(error) { + try { + if (typeof error === 'object' && error !== null) { + return { + name: error.name, + message: error.message, + stack: error.stack, + data: error.data + }; + } + } catch (e) { + // NOP + } + return { + value: error, + hasValue: true + }; + } + _serializeMulti(array) { for (let i = 0, ii = array.length; i < ii; ++i) { const value = array[i];