用Jest模拟Shelljs-[TypeError:shell.exec不是函数] [英] Mocking shelljs with Jest - [TypeError: shell.exec is not a function]

查看:96
本文介绍了用Jest模拟Shelljs-[TypeError:shell.exec不是函数]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在上一个有关模拟的问题中提到的那样,我是Jest和测试的新手,并且似乎遇到了一些麻烦.

As mentioned in my previous question about mocking, I am new to Jest and testing and I seem to be getting some curveballs.

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

This time around I am having trouble mocking shelljs in my CLI application.

自动模拟jest.mock('shelljs');无法正常工作,并报错为:[TypeError:shell.exec不是函数]

Automocking jest.mock('shelljs'); didn't work and errored as:[TypeError: shell.exec is not a function]

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

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

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

To my surprise I am still getting the same error message

任何指针都会受到赞赏.

Any pointers would be much apprecieted.

更新08/04/2020 :

根据下面的Teneff的回复,该模拟在以下情况下可以正常工作

As per Teneff's reply below, the mocking works fine with:

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

现在我正在超时,因为我对shell.exec()的调用是异步的,并且有一个可解决我的诺言的回调.

Now I'm getting timeouts as my call of shell.exec() is async and have a callback that resolves my promise.

我的目标是模拟shell.exec()来解决诺言,但这会导致等待和Jest超时.

My goal is to mock shell.exec() to just resolve the promise, but it goes into waiting around and Jest times out.

推荐答案

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

As you're using shell as an object with .exec property your jest.mock factory function should return an object with exec property

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

这篇关于用Jest模拟Shelljs-[TypeError:shell.exec不是函数]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆