NightmareJS多重评估

Hel*_*nda 6 javascript mocha.js chai nightmare

当我运行一个评估时,NightmareJS运行良好,但当我与页面交互时,我需要做更多的评估.然而,使用文档我尝试了一个链接评估的简单示例,我得到一个错误:

describe('test google search results', function() {
  this.timeout(15000);
  it('should find the nightmare github link first', function(done) {
    var nightmare = Nightmare({show: true})
    nightmare
      .goto('http://google.com')
      .wait(1000)
      .type('form[action*="/search"] [name=q]', 'github nightmare')
      .click('form[action*="/search"] [type=submit]')
      .wait(1000)//.wait('#rcnt')
      .evaluate(function () {
        return document.querySelector('div.rc h3.r a').href
      })
      .then(function(link) {
        console.log("TESTING 1");
        expect(link).to.equal('https://github.com/segmentio/nightmare');
      })
      .wait()
      .evaluate(function () {
        return document.querySelector('div.rc h3.r a').href
      })
      .end()
      .then(function(link) {
        console.log("TESTING 2");
        expect(link).to.equal('https://github.com/segmentio/nightmare');
        done();
      })
  });
});
Run Code Online (Sandbox Code Playgroud)

错误:

TypeError:nightmare.goto(...).wait(...).type(...).click(...).wait(...).evaluate(...).then(.. .).等待不是一个功能

在这种情况下,我在下一次评估之前添加了一个等待,以防我需要让系统等待完成,但仍然无法正常工作.

fel*_*gdr 7

事情是evaluate()返回一个Promise,这是一个Javascript的东西,而不是一个梦魇的东西.

所以Promise有一个thencatch其他方法,但显然没有wait方法.

我的回答是这个,这个资源可以帮助你更好地理解这个概念.

将概念应用于您的场景,代码将如下所示

describe('test google search results', function() {
  this.timeout(15000);
  it('should find the nightmare github link first', function(done) {
    var nightmare = Nightmare({show: true})

    nightmare
      .goto('http://google.com')
      .wait(1000)
      .type('form[action*="/search"] [name=q]', 'github nightmare')
      .click('form[action*="/search"] [type=submit]')
      .wait(1000)//.wait('#rcnt')
      .evaluate(function () {
        return document.querySelector('div.rc h3.r a').href
      })
      .then(function(link) {
        console.log("TESTING 1");
        expect(link).to.equal('https://github.com/segmentio/nightmare');

        nightmare.evaluate(function () {
          return document.querySelector('div.rc h3.r a').href
        })
        .end()
        .then(function(link) {
          console.log("TESTING 2");
          expect(link).to.equal('https://github.com/segmentio/nightmare');
          done();
        })

      }).catch(function(error) {
        done(new Error(error))
      })
  });
});
Run Code Online (Sandbox Code Playgroud)

注意第二次调用evaluate是如何在第一个then回调中进行的.