Search code examples
jsdomreadystate

Workarounds for jsdom document.readyState being readOnly?


I'm using mocha with jsdom for unit testing of a JavaScript library. One of the modules in the library has different behavior depending on whether or not the document is ready. In order to test that behavior, I need to simulate a document that isn't completely ready (i.e. it's readyState property is "loading"). The simple solution

delete document.readyState
document.readyState = 'loading'
// perform tests ...

doesn't work because jsdom treats the readyState property as readOnly. Even after that code the readyState remains "complete"

Has anyone come across any clever work-arounds for this limitation?


Solution

  • Just like a browser, you cannot delete or set document.readyState. Just like in a browser, you can change what the getter returns by redefining it:

    Object.defineProperty(document, "readyState", {
      get() { return "loading"; }
    });