【问题标题】:Is it possible to mock local functions using Jest是否可以使用 Jest 模拟本地函数
【发布时间】:2018-08-01 21:12:33
【问题描述】:

我在同一个文件中有一个包含 3 个函数的文件 (file.js):

file.js:

const fn1 = (number) => {
    return number + 1;
}

export const fn2 = (value) => {
    return value;
}

export const fn3 = (number) => {
    return fn1(number);
}

export const fn4 = (number) => {
    return fn2(number);
}

是否可以使用 JEST 定期模拟这些函数?我希望实现的目标是:

file.test.js:

import { fn2, fn3, fn4 } from 'file.js';

describe('fn2', () => {
  test('normal test.' => {
    expect(fn2(1)).toBe(1);
  })
});

describe('fn3', () => {
  test('mock fn1 for this test.' => {
    mock fn1 = () => { return 1 };

    expect(fn3(2)).toBe(1);
  })
});

describe('fn4', () => {
  test('mock fn2 for this test.' => {
    mock fn2 = () => { return 1 };

    expect(fn4(2)).toBe(1);
  })
});

【问题讨论】:

  • 您只能模拟导出的函数(否则,就测试而言,它甚至可能不存在)。您可以将 fn1 移动到单独的模块,然后对其进行模拟。

标签: node.js reactjs jestjs


【解决方案1】:

通过 JS 模块的工作方式是不可能的。只有导出的函数对外可见,其他的东西只在模块范围内可见,所以没办法mock。此外,无需模拟此函数,因为您只想测试公共 API。

测试函数本身并为这个模块模拟它的唯一方法是将它放入一个自己的模块中,如果它是一个非常复杂的函数,你需要良好的测试覆盖率并且获得它很复杂,那么这是有道理的当它在另一个模块中时。

【讨论】:

  • 感谢 Andreas 的澄清。
猜你喜欢
  • 1970-01-01
  • 2020-03-31
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多