1

I want to test in AVA a method that use global "document", eg.

export const blurActiveElement = (): void => {
    if (typeof window.focus === 'function') {
        window.focus();
    }
    if (document.activeElement) {
        if (typeof (document.activeElement as HTMLElement).blur === 'function') {
            (document.activeElement as HTMLElement).blur();
        }
    }
};

I have tried:

import test from 'ava';
import { JSDOM } from 'jsdom';
import { blurActiveElement } from '.';

test.before(() => {
    const dom = new JSDOM('<!DOCTYPE html><html><head></head><body><div id="my-element-id"></div></body></html>')
    globalThis.window = dom.window
    globalThis.document = dom.window.document
    globalThis.customElements = window.customElements
    globalThis.HTMLElement = window.HTMLElement
})

test('blurActiveElement', (t) => {
    const el = document.getElementById('my-element-id');
    el.focus();
    t.is(document.activeElement == el, true);
    blurActiveElement();
    t.is(document.activeElement == el, false);
});

but the console show this error:

Error thrown in test:

TypeError {
  message: 'Cannot set property window of #<Object> which has only a getter',
}

on this line:

globalThis.window = dom.window

How set up AVA for works with JSDOM?

ar099968
  • 6,963
  • 12
  • 64
  • 127

0 Answers0