【问题标题】:How to mock javascipt new Date to return different date from browser console如何模拟 javascript new Date 从浏览器控制台返回不同的日期
【发布时间】:2022-01-26 17:18:38
【问题描述】:

我使用的网站在不同的日期显示不同的内容。在 JavaScript 中,它使用new Date() 来确定当前日期,并使用它来确定要显示的内容。

如果我想查看其他日期的内容,我可以更改我的系统时间。但是,这很乏味并且会干扰其他应用程序。我试图弄清楚是否有一些代码可以在浏览器的 javascipt 控制台中运行,这些代码将模拟 new Date() 以返回我选择的日期

我看到有一些问题讨论用玩笑在 Date 上创建间谍,但我没有看到在我的浏览器控制台中模拟这个的方法

【问题讨论】:

  • 什么时候使用new Date?在页面加载?如果是这样,您将很难在页面代码运行之前运行任何可以模拟 Date 的东西(缺少编写浏览器扩展程序)。
  • 当然可以,如果需要的话我可以把js打包成浏览器扩展

标签: javascript date jestjs mocking


【解决方案1】:

可以将Date 函数替换为您自己的函数来提供您想要的结果,但是在页面使用它之前这样做会很棘手,除非您编写浏览器扩展程序。

基本位是(见 cmets):

// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
    // Called via `new`?
    if (!new.target) {
        // No, just pass the call on
        return OriginalDate(...args);
    }
    // Determine what constructor to call
    const ctor = new.target === Date ? OriginalDate : new.target;
    // Called via `new`
    if (args.length !== 0) {
        // Date constructor arguments were provided, just pass through
        return Reflect.construct(ctor, args);
    }
    // It's a `new Date()` call, mock the date we want; in this
    // example, Jan 1st 2000:
    return Reflect.construct(ctor, [2000, 0, 1]);
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
    value: OriginalDate.length,
    configurable: true
});

// Save the original `Date` function
const OriginalDate = Date;
// Replace it with our own
Date = function Date(...args) {
    // Called via `new`?
    if (!new.target) {
        // No, just pass the call on
        return OriginalDate(...args);
    }
    // Determine what constructor to call
    const ctor = new.target === Date ? OriginalDate : new.target;
    // Called via `new`
    if (args.length !== 0) {
        // Date constructor arguments were provided, just pass through
        return Reflect.construct(ctor, args);
    }
    // It's a `new Date()` call, mock the date we want; in this
    // example, Jan 1st 2000:
};
// Make our replacement look like the original (which has `length = 7`)
// You can't assign to `length`, but you can redefine it
Object.defineProperty(Date, "length", {
    value: OriginalDate.length,
    configurable: true
});

console.log("new Date()", new Date());
console.log("new Date(2021, 7, 3)", new Date(2021, 7, 3));

【讨论】:

    【解决方案2】:

    您可以使用它在加载之前修改内容: https://developer.chrome.com/docs/extensions/reference/webRequest/

    有一个我没有使用过的扩展可能可以做到: https://chrome.google.com/webstore/detail/page-manipulator/mdhellggnoabbnnchkeniomkpghbekko?hl=en

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-04
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      相关资源
      最近更新 更多