如何在量角器中更改浏览器日期

时间:2017-10-11 04:41:16

标签: protractor

我的用例是我有一个阻止操作B的UI,除非在上一个日历月中发生操作A(会计生命周期疯狂 - 无所谓)。

我正在编写一个测试,验证操作B是否正常工作,但我无法执行操作B正在工作,除非我有上个月发生的操作A.我的量角器设置运行在真正的API之上,而模拟数据不是我将考虑的选项(如果我选择模拟API响应,这将更容易)。

API不允许我操作操作A的创建/更新日期,因此我测试此方案的选项是操作底层数据库或在测试时将浏览器推送到下个月。假设我想采用浏览器方法,我怎样才能使用量角器?

1 个答案:

答案 0 :(得分:0)

一旦我有一个机制来操纵浏览器时间,那么我选择的解决方案是启动一个场景,执行操作A,将浏览器时间提前一个月,然后执行操作B.

这涉及使用量角器browser.executeScript在浏览器上下文中运行JS,并使用timeshift-js模块覆盖JS Date对象。

这是代码

此代码正在使用:

  • angular:1.5.10
  • 量角器:5.1.2
  • cucumber-js:1.3.3
  • timeshift-js:1.0.1

我可以写这样的场景:

Feature: Travelling in time

  Scenario: Scenario that manipulates time
    When I view some page
    And I check what time it is
    And I do operation A
    And I advance the browser by 1 days
    And I check what time it is
    Then I can do operation B

  Scenario: Scenario Double Check that the next scenario gets the correct time
    When I view the list of maintenance requests
    And I check what time it is

这是步骤实现。这里黄瓜没有什么特别的,所以应该很容易适应基于茉莉花或摩卡的describe / it框架:

const timeShiftLibraryString = fs.readFileSync(`path/to/node_modules/timeshift-js/timeshift.js`, 'utf-8')

module.exports = function () {

  this.When(/I advance the browser by (-?[0-9]+) (day|month)s?$/, function (offset, unit) {
    const now = moment()
    const future = moment().add(offset, unit)
    const amountOfMillisecondsToAdvanceBrowser = (future.unix() - now.unix()) * 1000
    const tolerance = 15 * 1000

    const advanceTime = function (futureOffsetInMilliseconds, timeShiftLibraryString) {
      // these two lines are only necessary because I dont want Timeshift in my production code, only during test
      const timeshiftLibrary = new Function(timeShiftLibraryString)
      timeshiftLibrary.call(window)

      Date = window.TimeShift.Date
      window.TimeShift.setTime(Date.now() + futureOffsetInMilliseconds)
      return Date.now()
    }

    return browser.executeScript(advanceTime, amountOfMillisecondsToAdvanceBrowser, timeShiftLibraryString).then((browserTime) => {
      const expectedTime = Date.now() + amountOfMillisecondsToAdvanceBrowser - tolerance
      this.logger.debug(`Time manipulation complete: browserTime = ${moment(browserTime)}`)
      if (browserTime >= expectedTime) {
        return Promise.resolve(browserTime)
      }

      return Promise.reject(new Error(`advanceTime did not work: reported browserTime: ${browserTime}. Expected Time: ${expectedTime}`))
    })
  })

  this.When(/I check what time it is/, function () {
    const whatTimeIsItInTheBrowser = function () {
      return Date.now()
    }
     return browser.executeScript(whatTimeIsItInTheBrowser).then((browserTime) => {
      console.log(`Browser Time = ${moment(browserTime)}`)
    })
  })
}

考虑: