【问题标题】:How to mock a library function call in typescript?如何在打字稿中模拟库函数调用?
【发布时间】:2020-02-21 05:14:39
【问题描述】:

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

下面是我需要模拟并将字符串返回为“澳大利亚/悉尼”的代码

moment.tz.guess()

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

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

【问题讨论】:

  • 你试过什么?介意发布一些示例吗?
  • 尝试使用 jest.mock 但无法这样做。更新了上面的帖子。

标签: javascript typescript mocking jestjs


【解决方案1】:

解决办法如下:

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

【讨论】:

    猜你喜欢
    • 2016-11-27
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    相关资源
    最近更新 更多