ES6 javascript tests using Tape and Nightmare.js

1.5k views Asked by At

I've been trying to test my ES6 code using Tape assertions and Nightmare.js to load a test page. I keep trying different ES6 methods: async/await, yield, generators, and I think I'm a bit over my head. I'm also not sure when and when to not use babel-tape. I can get the following test to pass, but the minute I create another evaluate block it errors out. The documentation is fairly scarce (or uses Mocha). What's the best practice here?

import {test} from "tape";
import {default as nightmare} from "nightmare";

const page = nightmare().goto("http://localhost:4000/index.html");

page.evaluate(() => document.getElementsByTagName("body").length).end()
  .then((result) => {
    test("detect page body", (assert) => {
      assert.equal(1, result);
      assert.end();
    });
  });

ps. I'm using babel-tape-runner to run the tests.

1

There are 1 answers

0
Ross On BEST ANSWER

I can get the following test to pass, but the minute I create another evaluate block it errors out.

Hm, you're calling .end() on the Nightmare instance. You shouldn't be interacting with that instance once it ends, that is probably causing you some of your problems.

The documentation is fairly scarce (or uses Mocha)

If you take a look at the test suite in Nightmare, the describe blocks have a beforeEach and afterEach that sets up or destroys the Nightmare instance, respectively. Your test - at least in my read - would set up a single Nightmare instance for all of your tests, which may lead to undesirable behavior.


All that said, you might want to try moving the declaration and usage of Nightmare internal to your tests. Off the cuff, something like:

import {test} from "tape";
import {default as Nightmare} from "nightmare";

test('detect page body', (assert) => {
 var nightmare = Nightmare();
 nightmare
    .goto("http://localhost:4000/index.html")
    .evaluate(() => document.getElementsByTagName("body").length)
    .then((result) => {
      assert.equal(1, result);
      nightmare.end(()=>{
        assert.end();
      });
    });
});