Hay un sitio web que uso que muestra contenido diferente en fechas diferentes. En JavaScript, usa new Date() para determinar la fecha actual, que usa para determinar qué contenido mostrar.
Si quisiera ver contenido de una fecha diferente, puedo cambiar la hora de mi sistema. Sin embargo, esto es tedioso e interfiere con otras aplicaciones. Estoy tratando de averiguar si hay algún código que pueda ejecutar en la consola javascipt del navegador que se burlará de la new Date() para devolver la fecha de mi elección
Veo que hay algunas preguntas que tratan sobre la creación de un espía en Date with jest, pero no veo una forma de simular esto en la consola de mi navegador.
Es posible reemplazar la función Date con su propia función que proporcione los resultados que desea, pero hacerlo antes de que la página la use será complicado a menos que escriba una extensión de navegador.
La parte fundamental es (ver comentarios):
// 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));Puede usar esto para modificar el contenido antes de que se cargue: https://developer.chrome.com/docs/extensions/reference/webRequest/
Existe esta extensión que no he usado que puede hacerlo: https://chrome.google.com/webstore/detail/page-manipulator/mdhellggnoabbnnchkeniomkpghbekko?hl=en
gracias @tj-crowder 🙏 por la mejor solución que he encontrado hasta ahora... Hice algunas personalizaciones para que Date.now también funcione.
También un consejo, coloque el punto de interrupción al comienzo de su secuencia de comandos, ejecute el código en la consola y reanude la ejecución para obtener la mejor consistencia de fecha 😌
mi modificación:
// Save the original `Date` function const OriginalDate = Date; const fakeDateArgs = [2022, 5, 3]; // beware month is 0 based let fakeDate; // 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 fakeDate = Reflect.construct(ctor, fakeDateArgs); return fakeDate; }; // 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 }); Object.defineProperty(Date, "now", { value: () => fakeDate.getTime(), configurable: true });