I'm attempting to use Nightmare to test front-end code which will eventually manipulate an SVG client-side. I'm using jest to write these tests.
I'm attempting to define an asynchronous utility function which I can use as an interface to Nightmare's evaluate
.
So for example, I'd like to be able to write a test like the following (modeled after Jest's documentation of how to test asynchronous functions):
test("2 + 2 should be 4 in the browser", async function() {
expect.assertions(1);
let returnValue = await runInBrowser(function() {
return 2 + 2;
});
expect(returnValue).toEqual(4);
});
Currently, I've done this by creating a function, runInBrowser
, which returns Nightmare's evaluate
having been run in the context of a blank HTML page, i.e.
runInBrowser = function(fn) {
// Example drawn from the `visit` module imported at https://github.com/vigetlabs/jest-with-nightmare
let page = nightmare();
// Relying on basic `foo.html` page for testing and to offer an environment; I believe we need to `goto` a URL to have an environment to evaluate in.
return page.goto("file://" + __dirname + "/foo.html").evaluate(fn);
};
where foo.html
is a blank HTML page.
Now, with this in hand I'd like to test my code as it will run on the front-end. I'm using browserify
to generate a bundle via browserify index.js --standalone
. I plan to then include that bundle on the front-end via <script src=…>
.
My question is this: Given that browserify will create a bundle I'd include on the front-end (say, exporting the method foo
in a given JS file as Bar.foo
, if my standalone bundle is Bar
), how do I test foo
within Nightmare? A unit tests of foo
in jest, to be evaluated in the browser's context, would require me to test Bar.foo
, but Bar
won't have been imported into my test (even if I include Bar
in the HTML page that my helper function opens).
This all feels quite messy for what I assume is a very common need: using jest to unit test browserified code that must be run in a browser context. So, I assume I'm doing something wrong. Any advice (or pointers to samples or templates) would be appreciated.