如何模拟jest中未安装的npm包?
我正在编写一个库,我需要测试一些未安装可选依赖项的情况。
更新
我的库有一个可选的依赖项。我的库的最终用户可以选择安装 styled-components
。
在我的测试(开 Jest )中,我介绍了安装 styled-components
时的情况。
现在我需要覆盖未安装包时的情况。
test(`When styled-components is not installed`, () => {
process.env.SC_NOT_INSTALLED = true
const fn = () => {
const styled = require(`./styled`)
}
expect(fn).toThrow(Error)
})
let styled
try {
require.resolve(`styled-components`)
styled = require(`styled-components`)
if (process.env.NODE_ENV === `test` && process.env.SC_NOT_INSTALLED) {
throw new Error(`Imitation styled-components is not installed`)
}
}
catch {
styled = () => {
throw new Error(`Module not found: styled-components`)
}
}
export default styled
process.env.SC_NOT_INSTALLED
-> 将不起作用,因为我猜测试正在不同的进程中运行。
最佳答案
当您的 try
中抛出异常时,您正在导出一个函数。
调用导出的函数会引发错误
。
将您的测试更改为:
test(`When styled-components is not installed`, () => {
process.env.SC_NOT_INSTALLED = true;
const styled = require(`./styled`).default;
expect(() => styled()).toThrow('Module not found: styled-components'); // Success!
});
...它应该可以工作。
更新
如果您在同一个测试文件中多次调用 require('./styled')
,那么您将需要添加一个调用 jest.resetModules
的 afterEach
。 ,否则 Jest
将缓存该模块,并为每个 require
继续返回相同的模块:
afterEach(() => {
jest.resetModules();
})
test(`When styled-components is installed`, () => {
const styled = require(`./styled`).default;
// ...
});
test(`When styled-components is not installed`, () => {
process.env.SC_NOT_INSTALLED = true;
const styled = require(`./styled`).default;
expect(() => styled()).toThrow('Module not found: styled-components'); // Success!
});
关于javascript - 如何在 Jest 中模拟未安装的 npm 包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55411559/