2017-10-11 61 views
0

我的用例是我有一個UI,它可以防止操作B,除非在前一個日曆月發生操作A(會計生命週期的瘋狂 - 無所謂)。如何更改量角器中的瀏覽器日期

我正在編寫一個測試,驗證操作B是否正常工作,但我不能執行操作B正在工作,除非我有上個月發生的操作A.我的量角器設置在真實的API上運行,並且模擬數據不是我會考慮的選項(如果我選擇模擬API響應,這將更容易)。

這些API不允許我操作操作A的創建/更新日期,因此測試此場景的選項是操縱底層數據庫或在測試時將瀏覽器推入下個月。假設我想採用瀏覽器的方法,我怎麼才能使用量角器來處理這個問題?

回答

0

一旦我有一個機制來操控瀏覽器的時候,然後我選擇瞭解決辦法是啓動方案,執行操作A,提前瀏覽器時一個月的未來,然後再執行操作B.

這涉及使用量角器browser.executeScript在瀏覽器上下文中運行JS,並使用timeshift-js模塊覆蓋JS Date對象。

下面是代碼

該代碼被使用:

  • 角:1.5.10
  • 量角器:5.1.2
  • 黃瓜-JS:1.3.3
  • 時移-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 

這裏是執行步驟。這裏沒有什麼具體的黃瓜,所以應該根據描述/ 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)}`) 
    }) 
    }) 
} 

注意事項: