Aneesa Saleh
Aneesa Saleh

Reputation: 35

Chai assert.deepEqual throws error "TypeError: Right-hand side of 'instanceof' is not an object" when using atob

I'm using Chai and Mocha to run tests on my helper functions. I used JSDOM to include atob and btoa. This is my setup.js file:

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

global.window = window;
global.document = window.document
global.btoa = window.btoa;
global.atob = window.atob;

When I try to run my tests, I get this error:

TypeError: Right-hand side of 'instanceof' is not an object.

My test function:

describe('helpers', () => {
  const testObject = { id: 1 };
  const encodedObject = base64EncodeObject(testObject);
  const decodedObject = base64DecodeObject(encodedObject);
  
  describe('base64DecodeObject()', () => {
    it('decoded object should match original object', () => {
      assert.deepEqual(decodedObject, testObject);
    });
  });
});

Target function:

const base64DecodeObject = (base64String) => {
  let object = atob(base64String);
  object = JSON.parse(object);
  return object;
}

Upvotes: 2

Views: 1518

Answers (1)

Louis
Louis

Reputation: 151391

Your problem is caused by the fact that you're only going only part-way towards mimicking a DOM environment in Node. You set a few variables and stop there, and so you end up with something which is neither a stock Node environment, nor a DOM environment.

chai uses deep-eql to perform deep comparison, and deep-eql uses a package named type-detect to do some of its work. type-detect performs a test that indicates to it that it is running in a DOM environment and eventually it tries to do this:

if (obj instanceof globalObject.HTMLElement && obj.tagName === 'BLOCKQUOTE') {

Since you did not copy HTMLElement from window to global, then it fails with the error you get. You can fix it by adding:

global.HTMLElement = window.HTMLElement;

Upvotes: 7

Related Questions