walmartlabs / little-loader

A lightweight, IE8+ JavaScript loader
MIT License
370 stars 28 forks source link

Cannot read property 'parentNode' of undefined #53

Closed cedricdelpoux closed 7 years ago

cedricdelpoux commented 7 years ago

When I try to test my loading function using Jest, I get this error.

TypeError: Cannot read property 'parentNode' of undefined

      at _addScript (node_modules/little-loader/lib/little-loader.js:43:17)
      at _lload (node_modules/little-loader/lib/little-loader.js:209:7)

I found this error in an old issue too #37 .

What is your recommandation to test your lib using a test runner like Jest ? Thank you

exogen commented 7 years ago

Since Jest uses JSDOM instead of a real browser environment, it won't have an actual <script> in the document like you'd find in a real scenario (there will only be an empty placeholder document created by JSDOM).

I can think of a couple options:

  1. Normally you can configure the document to use with JSDOM and you'd be able to fix this there, but I think Jest hides that setup from us. So use JDOM to append an empty <script> tag to the document in the setup/before method of your test. That way the document will reflect what a real browser's would look like. This could look like:
    before(() => {
    const script = document.createElement('script');
    document.body.appendChild(script);
    })
  2. Mock out little-loader since you're sort of testing too much by actually calling it – if it's a unit test you really only want to test your own code. It's also often considered bad practice for your test suite to actually hit the network (for this reason, I might recommend mocking out little-loader even if your tests were running in a real browser environment and working). In Jest you can use mock.fn() to do this.
cedricdelpoux commented 7 years ago

Thank you very much, the first solution works for me