zoukankan      html  css  js  c++  java
  • nightwatch系列教程02——开发者指南:使用Nightwatch

    本章内容翻译自http://nightwatchjs.org/guide#using-nightwatch

    编写测试

    在页面上使用推荐的CSS选择器,nightwatch让编写自动化测试变得很简单。
    在你的项目中创建一个独立的文件夹,比如:tests。这里面的每个文件都会被nightwatch的测试运行器加载运行。一个基础的测试文件长这样:

    module.exports = {
      'Demo test Google' : function (browser) {
        browser
          .url('http://www.google.com')
          .waitForElementVisible('body', 1000)
          .setValue('input[type=text]', 'nightwatch')
          .waitForElementVisible('button[name=btnG]', 1000)
          .click('button[name=btnG]')
          .pause(1000)
          .assert.containsText('#main', 'Night Watch')
          .end();
      }
    };

    为了让Selenium会话可以正常关闭,当你想结束测试的时候,记住要调用 .end() 方法

    如果需要的话,一个测试文件也可以包含多个步骤:

    module.exports = {
      'step one' : function (browser) {
        browser
          .url('http://www.google.com')
          .waitForElementVisible('body', 1000)
          .setValue('input[type=text]', 'nightwatch')
          .waitForElementVisible('button[name=btnG]', 1000)
      },
    
      'step two' : function (browser) {
        browser
          .click('button[name=btnG]')
          .pause(1000)
          .assert.containsText('#main', 'Night Watch')
          .end();
      }
    };

    测试文件也可以按照这种格式来写:

    
    this.demoTestGoogle = function (browser) {
      browser
        .url('http://www.google.com')
        .waitForElementVisible('body', 1000)
        .setValue('input[type=text]', 'nightwatch')
        .waitForElementVisible('button[name=btnG]', 1000)
        .click('button[name=btnG]')
        .pause(1000)
        .assert.containsText('#main', 'The Night Watch')
        .end();
    };

    使用XPath选择器

    Nightwatch 同样也支持 xpath 选择器。通过下面的例子可以看到,使用 useXpath() 就可以切换成 xpath 作为你的元素定位策略。切换回 css 选择器,调用 useCss() 即可。

    如果你想将 xpath 作为你的默认选择器的话,在你的test setting中,设置属性 “use_xpath”: true 即可。

    this.demoTestGoogle = function (browser) {
      browser
        .useXpath() // every selector now must be xpath
        .click("//tr[@data-recordid]/span[text()='Search Text']")
        .useCss() // we're back to CSS now
        .setValue('input[type=text]', 'nightwatch')
    };

    BDD Expect 断言

    Nightwatch从版本v0.7开始引入了一个新的BDD风格的断言库,它极大地提高了断言的灵活性和可读性。

    expect断言使用来自 Chai 框架的Expect api的子集,此时仅可用于元素。 这是一个例子:

    module.exports = {
      'Demo test Google' : function (client) {
        client
          .url('http://google.no')
          .pause(1000);
    
        // 期望body元素1000ms后显示
        client.expect.element('body').to.be.present.before(1000);
    
        // 期望id为lst-ib的元素拥有display的css属性
        client.expect.element('#lst-ib').to.have.css('display');
    
        // 期望body元素的class属性中包含vasq
        client.expect.element('body').to.have.attribute('class')
        .which.contains('vasq');
    
        // 期望id为lst-ib的元素是一个input
        client.expect.element('#lst-ib').to.be.an('input');
    
        // 期望id为lst-ib的元素可见
        client.expect.element('#lst-ib').to.be.visible;
    
        client.end();
      }
    };

    expect接口为定义断言提供了更加灵活和流畅的语言,与现有的断言接口相比有了显着的改进。 唯一的缺点是不再可能链接断言,并且此时尚不支持自定义消息。

    有关可用expect断言的完整列表,请参阅 API 文档。

    使用 before[Each] and after[Each] 钩子

    Nightwatch 为测试文件提供了标准的 before/afterbeforeEach/afterEach 钩子。
    before 和 after 钩子分别会在测试套件(test suite)执行之前和之后执行,而beforeEach 和 afterEach 则会在每个测试用例/步骤(test step)之前和之后执行。

    所有钩子函数都有一个Nightwatch的实例作为参数。
    例子:

    module.exports = {
      before : function(browser) {
        console.log('Setting up...');
      },
    
      after : function(browser) {
        console.log('Closing down...');
      },
    
      beforeEach : function(browser) {
    
      },
    
      afterEach : function() {
    
      },
    
      'step one' : function (browser) {
        browser
         // ...
      },
    
      'step two' : function (browser) {
        browser
        // ...
          .end();
      }
    };

    在这里例子中,各个方法的调用顺序:before(), beforeEach(), "step one", afterEach(), beforeEach(), "step two", afterEach(), after()

    出于向后兼容性原因,afterEach 钩子只能以异步的形式接收browser参数,像这样子:
    afterEach(browser, done) { .. }

    异步的 before[Each] 和 after[Each]

    所有的 before[Each]after[Each] 都可以用来进行异步的操作,这时需要接收一个回调函数作为第二个参数。

    当一个异步操作结束的时候,done函数必须作为最后一步被调用。否则将会导致timeout的错误。

    一个包含 beforeEach 和 afterEach 的例子

    module.exports = {
      beforeEach: function(browser, done) {
        // performing an async operation
        setTimeout(function() {
          // finished async duties
          done();
        }, 100);
      },
    
      afterEach: function(browser, done) {
        // performing an async operation
        setTimeout(function() {
          // finished async duties
          done();
        }, 200);
      }
    };

    控制 done函数的调用超时

    默认情况下done的超时时间是10秒(单元测试是2s)。但某些情况下这是不够的,为了避免timeout错误,你可以在外部的全局设置文件中,通过定义一个asyncHookTimeout的属性(以毫秒为单位)增加这个时长。你可以参考这个外部全局变量的配置例子:globalsModule

    指定特定的测试失败

    故意的让一个测试失败可以通过给done传递一个Error参数来实现。

    module.exports = {
      afterEach: function(browser, done) {
        // performing an async operation
        performAsync(function(err) {
          if (err) {
            done(err);
          }
          // ...
        });
      }
    };

    外部的全局变量

    大多数情况下,通过globals_path属性中指定一个外部blobal文件来定义全局变量,会比在nightwatch.json中定义更有用。你可以根据需要覆盖每个环境的全局变量。假设你在本地运行测试,并且还在远程服务器上运行。大多数时候你需要一些不同的设置。

    全局钩子

    在测试范围之外,全局也可以使用与测试套件相同的一组钩子。在全局钩子的情况下,beforeEachafterEach 引用测试套件(即测试文件,test suite),并在测试套件之前和之后运行。

    全局变量

    有一些测试配置的全局变量可以控制测试的执行。这是一个 globalsModule
    的例子。

    例子:

    module.exports = {
      'default' : {
        isLocal : true,
      },
    
      'integration' : {
        isLocal : false
      },
    
      // 外部的before钩子在整个测试的一开始运行,在创建Selenuim会话之前
      before: function(done) {
        // 只在本地运行
        if (this.isLocal) {
          // 启动本地服务器
          App.startServer(function() {
            // server listening
            done();
          });
        } else {
          done();
        }
      },
    
      // 外部的after钩子在整个测试的最后运行,在关闭Selenuim会话之后
      after: function(done) {
        // 只在本地运行
        if (this.isLocal) {
          // 关闭本地服务器
          App.stopServer(function() {
            // shutting down
            done();
          });
        } else {
          done();
        }
      },
    
      // 这会在每个测试文件执行之前运行
      beforeEach: function(browser, done) {
        // 获取会话信息
        browser.status(function(result) {
          console.log(result.value);
          done();
        });
      },
    
      // 这会在每个测试文件结束之后执行
      afterEach: function(browser, done) {
        console.log(browser.currentTest);
        done();
      }
    };

    github

    本文发表在我的个人博客中,欢迎围观,发现其他干货~博客地址 https://jerryyuanj.github.io/

  • 相关阅读:
    python爬虫实战(八)--------知乎
    python爬虫实战(七)--------伯乐在线文章(模版)
    python分布式爬虫打造搜索引擎--------scrapy实现
    VS2010与SVN
    ASP.net 自定义控件GridView
    Asp.net Ajax提供PageMethods调用
    JSON串行化
    JOSN反串行化
    WebRequestManager对象的使用
    WebRequest调用
  • 原文地址:https://www.cnblogs.com/jerryyj/p/9621544.html
Copyright © 2011-2022 走看看