0
votes

I am unable to mock 3rd party function call in typescript. The third party library is moment-timezone and I want to mock the code to get browser timezone to write jest test.

Below is the code I need to mock and return string as 'Australia/Sydney'

moment.tz.guess()

I am trying to use jest.mock() as :-

jest.mock('moment-timezone', () => () => ({ guess: () => 'Australia/Sydney' }));
1
what have you tried with? Mind posting some examples?Joelgullander
Tried using jest.mock but unable to do so. Updated post above.Prerna shah

1 Answers

0
votes

Here is the solution:

index.ts:

import moment from 'moment-timezone';

export function main() {
  return moment.tz.guess();
}

index.spec.ts:

import { main } from './';
import moment from 'moment-timezone';

jest.mock('moment-timezone', () => {
  const mTz = {
    guess: jest.fn()
  };
  return {
    tz: mTz
  };
});

describe('main', () => {
  test('should mock guess method', () => {
    (moment.tz.guess as jest.MockedFunction<typeof moment.tz.guess>).mockReturnValueOnce('Australia/Sydney');
    const actualValue = main();
    expect(jest.isMockFunction(moment.tz.guess)).toBeTruthy();
    expect(actualValue).toBe('Australia/Sydney');
    expect(moment.tz.guess).toBeCalled();
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58548563/index.spec.ts
  main
    ✓ should mock guess method (6ms)

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