一旦我有一個機制來操控瀏覽器的時候,然後我選擇瞭解決辦法是啓動方案,執行操作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)}`)
})
})
}
注意事項: