如何模拟打字稿中的库函数调用?

时间:2019-10-24 20:13:56

标签: javascript typescript mocking jestjs

我无法在打字稿中模拟第三方函数调用。 第三方库是moment-timezone,我想模拟代码以获取浏览器时区来编写笑话测试。

下面是我需要模拟并以'Australia / Sydney'返回字符串的代码

moment.tz.guess()

我正在尝试将jest.mock()用作:-

jest.mock('moment-timezone', () => () => ({ guess: () => 'Australia/Sydney' }));

1 个答案:

答案 0 :(得分:0)

这是解决方案:

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();
  });
});

覆盖率100%的单元测试结果:

 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