Gil Tayar
Gil Tayar
Jul 29, 2017 · 1 min read

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:

  1. 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.
  2. 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.
  3. 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.

    Gil Tayar

    Written by

    Gil Tayar

    software developer ⚜ dad ⚜ nodejs and javascript fan ⚜ architect & evangelist at applitools ⚜ test all software! ⚜ and lots of love ❤️