我尝试使用黄瓜js自动执行某些测试,其中一个依赖于调用new Date()的函数。
我试图执行脚本并像这样覆盖日期。
const driver = (this.driver as ThenableWebDriver);
await driver.get(`http://localhost:5000/`);
await driver.executeScript(`
var d = new Date(2012,0,20);
Date = function(){return d;}
`);
如果我再次使用
调用executeScript函数await driver.executeScript(`
alert(new Date()) // returns the date i set
`);
新日期正确返回。 但是,当我模拟一次点击,并且onClick执行一个新的Date()时,它获取本地日期而不是我设置的日期。
任何提示? 提前致谢
[编辑]在此处看到了这一点:How to override new Date() on Protractor tests
var Date = (function() {
var OldDate = Date;
return function (){
return new OldDate(2012,0,20);
}
}());
但仍然没有运气。 executeScript在哪里运行?
答案 0 :(得分:1)
覆盖构造函数Date
:
await driver.executeScript(`
var Date = function() { // new constructor
return new window.Date.prototype.constructor(2013, 6, 14);
}
Date.prototype = window.Date.prototype; // inherit the methods from Date
Date.now = Date; // override Date.now()
Date.UTC = Date.prototype.constructor.UTC; // copy Date.UTC(...)
Date.parse = Date.prototype.constructor.parse; // copy Date.parse(...)
window.Date = Date; // override Date
`);