In theory you could run even integration tests that use (and even mutate) global values by using…
James Browning
11

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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.