Nannooskeeska
Nannooskeeska

Reputation: 157

Nightmare with Mocha: Uncaught TypeError: Cannot read property 'apply' of undefined

I'm trying to run an example test with Nightmare.js and Mocha, and I keep getting the error above. Here is the full output:

$ mocha nightmare-chai-example.js 


  Nightmare demo
    Start page
      1) should show form when loaded


  0 passing (716ms)
  1 failing

  1) Nightmare demo Start page should show form when loaded:
     Uncaught TypeError: Cannot read property 'apply' of undefined
      at Nightmare.done (/home/user/testing/node_modules/nightmare/lib/nightmare.js:313:14)
      at Nightmare.next (/home/user/testing/node_modules/nightmare/lib/nightmare.js:291:35)
      at /home/user/testing/node_modules/nightmare/lib/nightmare.js:301:46
      at EventEmitter.<anonymous> (/home/user/testing/node_modules/nightmare/lib/ipc.js:93:18)
      at ChildProcess.<anonymous> (/home/user/testing/node_modules/nightmare/lib/ipc.js:49:10)
      at handleMessage (internal/child_process.js:695:10)
      at Pipe.channel.onread (internal/child_process.js:440:11)

And here is the code that I'm running:

var path = require('path');
var Nightmare = require('nightmare');
var should = require('chai').should();

describe('Nightmare demo', function() {
  this.timeout(15000); // Set timeout to 15 seconds

  var url = 'http://example.com';

  describe('Start page', function() {
    it('should show form when loaded', function(done) {
      new Nightmare()
        .goto(url)
        .evaluate(function() {
          return document.querySelectorAll('form').length;
        }, function(result) {
          result.should.equal(1);
          done();
        })
        .run();
    });
  });
});

From this gist.

I'm running Ubuntu 16.04 LTS on an Oracle VM VirtualBox.

Upvotes: 0

Views: 3096

Answers (1)

Ross
Ross

Reputation: 2468

.run() expects a callback and will fail (with unhelpful output, as you have noticed) without it. This has been reported and a fix has been proposed.

It's also probably worth pointing out that .evaluate() does not work the way the gist you supplied describes, at least for versions >2.x. The .evaluate() method will try to send arguments after the evaluated function (the first argument) as arguments to that function.

Modifying the inside of your it call:

  new Nightmare()
    .goto(url)
    .evaluate(function() {
      return document.querySelectorAll('form').length;
    })
    .run(function(err, result){
      result.should.equal(1);
      done();
    });

It's also worth pointing out that .run() is for internal use, and it's been suggested for deprecation in favor of the Promise-like implementation using .then():

  new Nightmare()
    .goto(url)
    .evaluate(function() {
      return document.querySelectorAll('form').length;
    })
    .then(function(result){
      result.should.equal(1);
      done();
    });

Upvotes: 3

Related Questions