Javascript 如何模拟未安装的npm软件包?

Javascript 如何模拟未安装的npm软件包?,javascript,jestjs,Javascript,Jestjs,如何模拟中未安装的npm包 我正在编写一个库,需要测试一些未安装可选依赖项的情况 更新 我的库有一个可选的依赖项。my library的最终用户可以选择安装样式化组件 在我的测试(jest)中,我介绍了安装样式化组件时的情况。 现在,我需要介绍软件包未安装时的情况 test(`When styled components not installed`,()=>{ process.env.SC_NOT_INSTALLED=true 常数fn=()=>{ const styled=require(`

如何模拟中未安装的npm包

我正在编写一个库,需要测试一些未安装可选依赖项的情况

更新

我的库有一个可选的依赖项。my library的最终用户可以选择安装
样式化组件

在我的测试(jest)中,我介绍了安装
样式化组件时的情况。
现在,我需要介绍软件包未安装时的情况

test(`When styled components not installed`,()=>{
process.env.SC_NOT_INSTALLED=true
常数fn=()=>{
const styled=require(`./styled`)
}
expect(fn).toThrow(错误)
})
let样式化
试一试{
require.resolve(`styled components`)
styled=require(`styled components`)
if(process.env.NODE_env===`test`&&process.env.SC_未安装){
抛出新错误(`Simulation styled components not installed`)
}
}
抓住{
样式=()=>{
抛出新错误(`Module not found:styled components`)
}
}
导出默认样式

process.env.SC\u NOT\u INSTALLED
->将无法工作,因为我猜测试正在不同的进程中运行。

当在
try
中引发异常时,您正在导出函数

调用导出函数会抛出
错误

将您的测试更改为:

test(`When styled components not installed`,()=>{
process.env.SC_NOT_INSTALLED=true;
const styled=require(`./styled`)。默认值;
expect(()=>styled()).toThrow('modulenotfound:styled components');//成功!
});
…它应该会起作用


更新

如果在同一个测试文件中多次调用
require('./styled')
,则需要在每次调用后添加一个
,否则
Jest
将缓存模块,并继续为每个
require
返回相同的模块:

每次(()=>{ jest.reset模块(); }) 测试(`When styled components is installed`,()=>{ const styled=require(`./styled`)。默认值; // ... }); 测试(`When styled components not installed`,()=>{ process.env.SC_NOT_INSTALLED=true; const styled=require(`./styled`)。默认值; expect(()=>styled()).toThrow('modulenotfound:styled components');//成功! });
您是在询问如何模拟未安装的库,还是询问如何模拟已安装的库,使其看起来像未安装的库。请用代码和测试更新你的问题,让我们可以用它来回答。@brian住在户外。不,这不是我的意思。我需要检查
try
catch
的两个部分。您的代码段只会首先引导
try
部分始终。我想测试
catch
。我答案中的测试测试问题@sultan中代码的catch当
try
中抛出错误时,它会落入
catch
中,并返回调用时抛出错误的函数。因此,上面的测试使
catch
运行,然后验证
catch
返回的函数在调用时是否抛出错误。让我知道这是否合理,如果您有任何问题@sultanThank感谢您帮助寻找解决方案@brian lives outdoor。您给定的代码是错误的。当您调用const styled=require(
/styled
)时,您永远不会在catch部分出现错误。首先,env.variable不影响其他进程。所以,成功永远是最重要的。啊……我想我知道为什么它不适合你。我敢打赌,在同一测试文件中较早安装时,您有一个测试,并且
Jest
正在缓存模块,并在未安装时返回相同的模块。我已经更新了上面的答案,告诉你如何解决这个问题@苏丹