【问题标题】:Mocking shelljs with Jest - [TypeError: shell.exec is not a function]用 Jest 模拟 shelljs - [TypeError: shell.exec 不是函数]
【发布时间】:2020-04-07 07:42:30
【问题描述】:

正如我在上一个关于模拟的问题中提到的,我是 Jest 和测试的新手,我似乎得到了一些曲线球。

这一次我无法在我的 CLI 应用程序中模拟 shelljs

Automocking jest.mock('shelljs'); 不起作用并报错为:[TypeError: shell.exec is not a function]

所以我继续尝试使用mockImplementation()

jest.mock('shelljs', () => {
  return jest.fn().mockImplementation(() => {
    return {
      exec: () => {}
    };
  });
});

令我惊讶的是,我仍然收到相同的错误消息

任何指针都会非常感激。

2020 年 8 月 4 日更新

根据以下 Teneff 的回复,模拟可以正常工作:

jest.mock('shelljs', () => {
  return {
    exec: jest.fn()
  };
});

现在我遇到了超时,因为我对 shell.exec() 的调用是异步的,并且有一个回调来解决我的承诺。

我的目标是模拟 shell.exec() 来解决承诺,但它会等待并且 Jest 超时。

【问题讨论】:

    标签: javascript node.js unit-testing testing jestjs


    【解决方案1】:

    接受 Teneff 的回答后,我意识到超时发生了,因为我成功地模拟了 shell.exec,但是我使用了它的异步版本 exec(command [, options] [, callback]),所以我尝试首先注销参数并且它起作用了。

    剩下的就是调用回调,瞧,我的测试成功了。

    jest.mock('shelljs', () => {
      return {
        exec: jest.fn((_, __, callback) => callback())
      };
    });
    

    【讨论】:

      【解决方案2】:

      当您使用 shell 作为具有 .exec 属性的对象时,您的 jest.mock 工厂函数应该返回一个具有 exec 属性的对象

      jest.mock('shelljs', () => {
        return { exec: jest.fn() }
      });
      

      【讨论】:

      • 不幸的是,这被完全忽略了,shell 只是继续尝试运行我的命令:S。非常令人沮丧。
      【解决方案3】:

      Teneff answer 为我工作。 但因为我想模拟不同的 shell 响应,所以我改进了它:

      const shelljs = require('shelljs');
      
      jest.mock('shelljs');
      
      describe('Run the test suite', () => {
        test('it should ...', async () => {
          shelljs.exec = jest.fn().mockImplementation(() => ({ code: 0 }));
          ...
          expect(...);
        });
        test('it should ...', async () => {
          shelljs.exec = jest.fn().mockImplementation(() => ({ code: 1 }));
          ...
          expect(...);
        });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-16
        • 2021-05-01
        • 1970-01-01
        • 2018-06-22
        • 2020-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多