True, and I tried something similar when I was trying to implement iframe support in our integration tests, but there are (as fas as I remember), a few caveats:
- require is not a global function — it is a per module one (that’s how it knows how to work when you give it relative paths). This means that injecting your require into the vm is problematic.
- When you inject your require into the vm, that means that your require cache, which stores all the modules already loaded is still alive, which means that the iframe (or in your case the test) is already warmed up with all the modules. Which is usually fine, but sometimes you want them to start from scratch. This is probably fine with tests, but it didn’t work for iframes.
- The most hard to understand one was the the fact that since you’re using the parent vm’s require, then a module loaded by that require, or coming from its cache, will use the globals (e.g. Array.prototoype) from that parent vm and not from the child vm. Which means that things like instanceof stop working sometimes because instanceof doesn’t work cross-realm boundaries — an Array from one realm/vm, is not equal to an array from another.
I’m not saying it couldn’t be made to work, and maybe multiple tests can be made to work easier than iframes, but just know that it’s not trivial due to the abovementioned issues.