cypresslocaledayjs

Replacing moment() with dayjs


I'm having problems with the locale when going from the deprecated Moment to DayJS in Cypress.

The original Moment() usage:

public moment(): Moment {
    const moment = Cypress.moment();
    moment.locale("nb-NO");
    return moment;
}

const in2Months = moment().add(2, "months");

This worked fine, and for instance "March" was replaced by "Mars".

However, when trying to use it the same way with days.js, the locale isn't changed:

public day() {        
    return dayjs().locale('nb-NO');
}

const in2Months = page.day().add(2, "months");

The result here is still "March". I've tried using just 'no' for the locale, with the same result.

What am I missing here?

UPDATE: As per the below answer:

import dayjs from "dayjs";
import 'dayjs/locale/nb'

const in2Months = dayjs().locale('nb').add(2, 'Month');

cy.log(in2monthstoString());

RESULT: Mon, 28 Mar 2022 12:39:29 GMT

...which is not in locale format.

Also, trying any variation of .month() I am always getting results in the number of the month. But I cannot get the name.


Solution

  • As mentioned in the Days JS github readme, you have to import the internationalisation that you intent to use, it will not be included by default. So I wrote a simple program to check this and it worked

    const dayjs = require('dayjs')
    import 'dayjs/locale/nb'
    
    describe('SO Ques', () => {
      it('SO Ques', () => {
        cy.log(dayjs().locale('nb').add(2, 'Month').format('MMMM'))
      })
    })
    

    Test Runner:

    test runner screenshot

    So your program should look like:

    const dayjs = require('dayjs')
    import 'dayjs/locale/nb'
    
    public day() {        
        return dayjs().locale('nb');
    }
    const in2Months = page.day().add(2, 'Month').format('MMMM');
    

    You can evaluate all the values in a function and then return it and then use it in your test like this:

    function date() {
        return {
            day: dayjs().locale('nb').add(2, 'Month').format('DD'),
            month: dayjs().locale('nb').add(2, 'Month').format('MMMM'),
            year: dayjs().locale('nb').add(2, 'Month').format('YYYY'),
        };
    }
    
    date().day //28
    date().month //mars
    date().year //2022