Tips for mocking constructors in AngularJS, specifically the Date() constructor

Trying to verify a function which receives millisSinceEpoch and gives back the time if it is today's date, otherwise it gives the date.

getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) {
  var date = new Date(millisSinceEpoch);
  if (date.toLocaleDateString() == new Date().toLocaleDateString()) {
    // The replace function removes 'seconds' from the returned time.
    return date.toLocaleTimeString().replace(/:\d\d /, ' ');
  }
  return date.toLocaleDateString();

I plan on verifying this by faking the Date() constructor, but I'm uncertain about how to fake a constructor using 'prototype'?

Furthermore, is there an alternate way to validate this ?

Answer №1

I make a conscious effort to avoid using Date or Math.random in my code.

Instead, I develop services that replace them so I can easily mock different scenarios by activating the mock module.

angular.module('my.date',[])
    .value('Date', Date);

angular.module('my.mock.date',[])
    .value('Date', function(){
        // mocking Date functionality
    });

(It's not necessary to mock every aspect of Date, just the parts that are relevant to your code...)

For more information, check out this issue on angular. Also, refer to this answer on stackoverflow.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

Sending multiple unique forms with the same structure using JavaScript and Ajax on a single PHP page

In my PHP page, there are 12 individual forms with unique form IDs, checkboxes, and dropdowns. Take a look at this image: https://i.stack.imgur.com/pODzk.png Each form has an Update Zone that fetches Name, Enable status, Time, Dim information, and sends ...

The pairing of RequireJS and Toaster

I am facing an issue with integrating Toaster into my demoApp that utilizes RequireJS. Below is the code snippet: (function () { require.config({ paths: { 'angular': 'bower_components/angular/angular', ...

Enhancing functionality in Javascript by employing prototype descriptor for adding methods

Code: Sorter.prototype.init_bubblesort = function(){ console.log(this.rect_array); this.end = this.rect_array.length; this.bubblesort(); } Sorter.prototype.init = function(array,sort_type){ this.rect_array = array; this.init_bubblesort(); } Wh ...

Following a Node/Npm Update, Sails.js encounters difficulty locating the 'ini' module

While developing an application in Sails.js, I encountered an authentication issue while trying to create user accounts. Despite my efforts to debug the problem, updating Node and NPM only resulted in a different error. module.js:338 throw err; ...

The Ng-include tag does not provide highlighting for its text

Within an ng-include template, I have a div that is not highlighting when hovered over. Although the cursor changes to a pointer when hovering over the text, attempting to click and drag to highlight it results in nothing happening. This issue is signific ...

When pressing the next or previous button on the slider, an error message pops up saying "$curr[action] is not a

I found this interesting Js fiddle that I am currently following: http://jsfiddle.net/ryt3nu1v/10/ This is my current result: My project involves creating a slider to display different ages from an array, such as 15, 25, 35, 45, 55. The goal is to show ...

Apache causes HTML download tag to malfunction

I have an HTML file that includes the following code: <a href="/Library/WebServer/Documents/file.zip" download="file.zip"> Download here </a> When I test this HTML page on Chrome, it successfully allows me to download the file. However, when ...

Using Parseint in a Vue.js method

For instance, let's say this.last is 5 and this.current is 60. I want the sum of this.last + this.current to be 65, not 605. I attempted using parseInt(this.last + this.current) but it did not work as expected. <button class="plus" @click="plus"&g ...

Updating div content dynamically with Jquery and PHP variable

How can I continuously update a div with the current date and time using PHP variable and Jquery? Here is my PHP file containing the variable date: <?php $date = date('d/m/Y H:i:s'); ?> And here's the code in my HTML file: <!DOCT ...

What are the steps to redirect from a nested route back to the top route using Node.js with Express?

Is there a way to redirect from a nested route to a top route in Express.js? In the following code snippet, how can we make the callback for the route /toproute/nested redirect to /profile instead of /toproute/profile? // app.js const express = require(& ...

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

How can I limit the input of string values from a Node Express request query?

export type TodoRequest = { order?: 'asc' | 'desc' | undefined; } export const parseTodoRequest = (requestData: ParsedQs): TodoRequest => { return { order: requestData.order as 'asc' | 'desc' | u ...

What are the best methods for preventing scss styles from leaking between pages?

I'm currently working on a project that includes the following files: /* styles/1.scss */ body { /* Some other styles not related to background-color */ } /* styles/2.scss */ body { background-color: blue; } // pages/one.js import "../styles/ ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result. highlightRepeatedText(str) { // Split the string into an ...

Sending the slider value from a website to a program when the slider is adjusted

I have been experimenting with programming an ESP32 to regulate the LED brightness using a slider. I've pieced together some information from tutorials found on and Currently, I've achieved the ESP32 connecting to my network, displaying the sli ...

New design for UI grid: eliminate sorting menu and right-align column headers

I came across a question similar to this one My goal is to eliminate the dropdown menu from the column headers and align the text of the headers to the right. .ui-grid-header-cell { text-align: right; } However, my current attempts result in the disap ...

Issue with NPM peer dependencies enforcement

Forgive me if this question seems basic - I am new to Meteor... I am creating an application using meteor 1.3.1 and following the Socially tutorial for guidance as it aligns closely with my needs. However, I am encountering a persistent error in my consol ...