Search code examples
javascriptcypressmomentjsimporterror

Using the moment.js to check the time on an element is not working


I need to check the time on element is the current time plus two hours. I found some suggestions, but I cannot get it to work.

This is my current code:

cy.window().then((win) => {
    const newTime = moment().add(+2, 'h').format('HH:mm')
    cy.get('[for="timefrom"]').should('be.visible').and('have.text', 'Time from: ')
    cy.get('#timefrom').should('be.visible').and('have.value', newTime)
})

and I have placed the moment.js file in my folder and imported it

import {} from "./moment.js";

When I run my test, I am getting the following error

moment is not defined.


Solution

  • The problem seems to be with your import:

    import{
       
    } from "./moment.js";
    

    mean as much as:

    import *nothing* from "./moment.js";
    

    Thus when calling any moment-function you get an error.

    What you need is:

    import moment from "./moment.js";
    

    That way, you import the entire moment module.

    "What are the brackets for?", one might ask. The curled brackets {} are used, when you want to use only specific parts of a module and reduce the build size for production.

    E.g: You have a module with 100 function, but you only need three of them, then you do the following:

    import {fancyFunction, awesomeFunction, mediocreFunction} from "./module.js";