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

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

我正在尝试 运行 使用 Nightmare.js 和 Mocha 进行示例测试,但我不断收到上述错误。这是完整的输出:

$ 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)

这是我 运行ning 的代码:

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();
    });
  });
});

来自 this gist.

我在 Oracle VM VirtualBox 上 运行ning Ubuntu 16.04 LTS。

.run() 需要一个回调,如果没有它将会失败(如您所注意到的那样,输出无用)。这是 reported and a fix has been proposed

可能还值得指出的是,.evaluate() 并不像您提供的要点所描述的那样工作,至少对于版本 >2.x 是这样。 .evaluate() 方法将尝试在计算后的函数(第一个参数)之后发送参数作为该函数的参数。

修改您的 it 调用的内部:

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

值得指出的是 .run() 是供内部使用的,并且有人建议 deprecation 使用 Promise-like 实现.then():

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