简体   繁体   English

如何嘲笑不存在的外部依赖

[英]How to do jest mocking for non-exist external dependency

I am trying to mock external dependency which is not yet published in npm repository.我正在尝试模拟尚未在 npm 存储库中发布的外部依赖项。

import Utils from 'external-dependency';
jest.mock('external-dependency', () => ({
default: ()=> jest.fn()
}));

Above jest mocking display following error since that dependency not yet exist.上面的笑话模拟显示以下错误,因为该依赖项尚不存在。

Cannot find module 'external-dependency'找不到模块“外部依赖”

How to mock non-exist dependency in Jest?如何在 Jest 中模拟不存在的依赖?

As stated in the reference ,参考文献所述

The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system第三个参数可用于创建虚拟模拟——系统中不存在任何模块的模拟

Also notice that jest.mock return value translates to CommonJS module by default.还要注意jest.mock返回值默认转换为 CommonJS 模块。 In case of ES module, it should be:在 ES 模块的情况下,它应该是:

jest.mock('external-dependency', () => ({
  __esModule: true,
  default: ()=> jest.fn()
}), {virtual: true});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM