Lücks
Lücks

Reputation: 3984

Mocking moment format with timezone in jest

I'm testing a service which formats a date based in a timezone, it's working perfectly, but when I'm running the tests, I'm receiving the error: moment_timezone_1.default(...).utcOffset(...).format is not a function

I already tried to develop in different approaches which I saw in StackOverflow, but none of them worked, the error message changes (split is not a function, for example).

What can I do to properly mock the moment for my case or use the moment without mocking, but working, obviously?

Here is the function which gives an error:


export function formatTimezone(date, timezone = '+00:00', format = '') {
    return moment(date)
        .utcOffset(timezone)
        .format(format);
}

Upvotes: 0

Views: 1011

Answers (1)

Klaycon
Klaycon

Reputation: 11070

According to the docs utcOffset(timezone) returns the offset (a number) when no argument is provided. It seems to also do this when null is provided - see below.

console.log(moment().utcOffset(0).format())
console.log(moment().utcOffset(null).format())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

You need to validate the timezone input to make sure utcOffset isn't returning a number before calling .format() on it.

Upvotes: 1

Related Questions