jest.mock() - 如何从配置库模拟 config.get()

Sho*_*bha 5 javascript jestjs

我有两个问题

  1. 我想模拟配置库中的 config.get() 以返回一个值
  2. config.get 的模拟返回值应该是从此刻生成的日期

我尝试了以下操作,但收到错误“不允许引用任何超出范围的变量。无效的变量访问:时刻”

说一下我的功能:

function test(configVariable) {
  const variable = config.get(configVariable)
}
Run Code Online (Sandbox Code Playgroud)

测试功能

jest.mock('config', () => ({
      default: {
        get: () => jest.fn().mockImplementation(() => {
          const dDate = moment();
          dDate.subtract(1, 'd');
          dDate.format('YYYY-MM-DD');
          return dDate;
        }),
      }
    }));
Run Code Online (Sandbox Code Playgroud)

有人可以帮我做同样的事情吗?提前感谢您的宝贵时间。

小智 0

我相信应该是

jest.mock('config', 'get').mockImplementation(() => {
  const dDate = moment();
  dDate.subtract(1, 'd');
  return dDate.format('YYYY-MM-DD'); // not sure if you want to return formatted date or not
}));
Run Code Online (Sandbox Code Playgroud)