当我编写测试以在 playwright 中运行时,我希望能够设置浏览器认为它在测试开始时的日期。有没有办法使用剧作家来实现这一目标?
问问题
1338 次
2 回答
3
更简单的解决方案
page.evaluate(() => {
Date.now = () => {
return 1609477200000; //Jan 1, 2021
};
});
于 2021-02-16T17:34:16.537 回答
1
您可以使用诸如TimeShift 之类的模拟工具。这段代码将注入 timeshift 库,然后将日期注入Feb 02 2012
:
const playwright = require("playwright");
(async () => {
let removed = false;
const browser = await playwright["chromium"].launch({headless: false});
const page = await browser.newPage();
await page.setContent('<a href="#" onclick="document.querySelector(\'span\').innerText = new Date().toString()">Test me</a><span></span>');
await page.click('a');
console.log(await page.innerText('span'));
await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/timeshift-js@1.1.1/timeshift.js'});
await page.evaluate(() => {
Date = TimeShift.Date;
TimeShift.setTime(1328230923000);
});
await page.click('a');
console.log(await page.innerText('span'));
browser.close();
})();
输出:
Fri Sep 18 2020 15:06:58 GMT-0300 (Argentina Standard Time)
Thu Feb 02 2012 22:02:03 GMT-0300
于 2020-09-18T18:08:21.650 回答