Imitate the moment() function with jest

I am attempting to simulate the behavior of moment() in order to prevent a snapshot test from failing due to the time of day. Within my <Header /> component, there is a function that utilizes moment() to display various greetings (Hello, Good morning, good evening, etc).

Here is my test function:

jest.mock('moment', () => moment().month(11).date(24)); //This should display "happy xmas"
it("Matching snapshot", () => {
    act(() => {
        container = shallow(<Header />);
    });
    expect(container).toMatchSnapshot();
});

However, when I execute the test, I encounter the following error:

ReferenceError: moment_1 is not defined

If I remove the jest.mock(....) line, the test runs successfully, but the results are dependent on the time of day.

Answer №1

Following the advice of @skyboyer, it is recommended to mock the JS native Date object instead of using the moment module. Below is a complete demonstration:

index.tsx:

import React from 'react';
import moment from 'moment';

export class Header extends React.Component {
  public render() {
    const date = moment()
      .month(11)
      .date(24);

    return <div>{date.toString()}</div>;
  }
}

index.spec.tsx:

import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import { Header } from './';

describe('Header', () => {
  it('match snapshot', () => {
    jest.spyOn(Date, 'now').mockReturnValueOnce(new Date('2019/11/24').getTime());
    const wrapper: ShallowWrapper = shallow(<Header></Header>);
    expect(wrapper.text()).toBe('Tue Dec 24 2019 00:00:00 GMT+0800');
    expect(wrapper).toMatchSnapshot();
  });
});

index.spec.tsx.snap:

// Jest Snapshot v1

exports[`Header match snapshot 1`] = `
<div>
  Tue Dec 24 2019 00:00:00 GMT+0800
</div>
`;

Upon running unit tests, the results show 100% coverage:

 PASS  src/stackoverflow/56425230/index.spec.tsx
  Header
    ✓ match snapshot (14ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        3.592s, estimated 7s

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

Error in Typescript: Attempting to access the property 'set' of an undefined value

Currently, I am in the process of setting up a basic example of push notifications on Android using Nativescript and Typescript. Although my code may seem a bit messy, I am struggling with properly rewriting "var Observable = require("data/observable");" a ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

The art of representing objects and generating JSON responses

As I dive into building a web application using NextJS, a versatile framework for both API and user interface implementation, I find myself pondering the best practices for modeling and handling JSON responses. Key Points In my database, models are store ...

What could be causing the getTotals() method to malfunction?

I have been working on a finance app that is designed to update the "income", "expenses", and "balance" tables at the top each time a new item is added by the user. However, the current code seems to be failing in updating these values correctly based on u ...

Accessing the menu

There are two main headings in my menu: Administration and Market https://i.sstatic.net/JbePq.png When I click on the Administration heading, submenus for Portfolio and Corporate Action are displayed https://i.sstatic.net/oyabv.png The issue I am facin ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...

Utilizing IonPage and DeepLinkMetadataType in Ionic 3 for tab navigation: Eliminating the need for tab-0

One of the pages on my site contains tabs that are only loaded when clicked: explore.html <ion-tabs> <ion-tab [root]="tab1Root" [tabTitle]="hotTitle" tabIcon="flame"></ion-tab> <ion-tab [root]="tab2Root" [tabTitle]="searchTitle ...

When utilizing DomSanitizer, Angular2 suddenly ceases to function properly

I've been working with Angular 2 and TypeScript. Everything was going well until I encountered an issue with my pipe, which is causing the DomSanitizer to interfere with the (click) event functionality. Even though the (click) code appears intact in ...

What is the best way to execute 2 statements concurrently in Angular 7?

My goal is to add a key rating inside the listing object. However, I am facing an issue where the rating key is not displaying on the console. I suspect that it might be due to the asynchronous nature of the call. Can someone help me identify what mistak ...

Angular unable to retrieve data using Angularfire2

Having trouble retrieving data from the Real time Database on firebase. Read and Write permissions are set to public so no authentication is needed. The npm compilation is successful, indicating that the Angular-CLI code is correct. Following the document ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

Access NgModel from NgForm

Is there a way to access the NgModel of a FormControl retrieved from the NgForm.controls object within its parent form, or directly from the form itself? Upon form submission, I pass the form as a parameter to a custom function: <form #myForm="ngForm" ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

Issue encountered in NestJS/TypeORM: Unable to modify the property metadata of #<Repository> as it only has a getter method

When attempting to launch my nestjstutorial app, I encountered the following error message. The backend is connected to a PostgreSQL database. TypeError: Cannot set property metadata of # which has only a getter at EntityManager.getCustomRepository (D:&b ...

I am facing an issue with the Angular2 Modal Form where it only displays the data but does

Hey there, I recently started diving into Angular and I'm loving the learning process. Currently, I've managed to successfully load a form into my Modal when clicking on "viewDetails". However, as soon as I modify the Form from <form ngNoFo ...

The function causes changes to an object parameter once it has been executed

I've encountered an issue with a function that is supposed to generate a string value from an object argument. When I call this function and then try to use the argument in another function, it seems to be getting changed somehow. Here is the code fo ...

Leverage the same JSDoc comment across multiple TypeScript interfaces

If I have the interfaces below: interface Foo { /** * A date string in the format `yyyy-MM-dd` */ archiveDate: string; } interface Bar { /** * A date string in the format `yyyy-MM-dd` */ publishDate: string; } The JSDoc descriptions f ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Incorporating optional fields into the form builder without being mandatory

For my current project on Ionic 4, I have implemented a form builder to create and validate forms. I have also included the [disabled] attribute in the form to disable it if all fields are not valid. However, I noticed that even if I do not add Validators ...