mantoni / mochify.js

☕️ TDD with Browserify, Mocha, Headless Chrome and WebDriver
MIT License
346 stars 57 forks source link

Rewrite: Support native JavaScript modules #249

Closed mantoni closed 2 years ago

mantoni commented 3 years ago

We have the --serve <dir> option already, which loads the given web page in the browser before injecting tests.

We could add a --inject-modules option (any better names?) that adds a <script type="module"> tag in the generated start page for each given file.

m90 commented 2 years ago

I think I would like to look into this (in case noone else started yet) as, quite frankly, I know nothing about ESM at all and it starts to get embarassing. Maybe I can use this to get up to speed.

There's one thing I do not fully understand here yet (probably a good demonstration of how I know nothing about ESM):

Assuming someone runs the following command:

mochify ./src/foo.test.js --driver puppeteer --inject-modules

and src/foo.test.js looks like this:

import * as assert from 'assert'
import * as foo from './foo.js'

describe('foo', function () {
  it('does not throw when calling bar', function () {
    assert.doesNotThrow(function () {
      foo.bar()
    })
  })
})

Mochify would then inject (I think?):

<script>/* mocha ... */</script>
<script>/* client ... */</script>
<script type="module">
  /* above test case */
</script>

What I am failing to understand now is the following: how does the test case resolve:

  1. modules like assert or other libraries without bundling
  2. source files like ./foo.js?

Is 1 even possible? Would 2 work out of the box in case users would pass --serve ./src or would this require extra setup to be taken (assuming that inlining the test cases would break import paths)? Would the source document instead need to load the files something like <script src="/foo.test.js" type="module"></script>?

mantoni commented 2 years ago

modules like assert or other libraries without bundling

That wouldn't work. There are already other solutions that generate mini-bundles on request. We could pass requested files through a bundler, if one is specified. Not sure here and it might be out of scope for Mochify.

Would the source document instead need to load the files something like ?

This is how I would do it, yes. A server is required anyway to be able to import anything with esm. I guess generating the script tags is all that is needed for now.