如何在jest中模拟未安装的npm包?
我正在编写一个库,我需要测试一些未安装可选依赖项的情况。
更新
我的库有一个可选的依赖项。我的库的最终用户可以选择安装styled-components
。
在我的测试(开玩笑)中,我介绍了安装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
中抛出异常时,您正在导出一个函数。
调用导出的函数会引发Error
。
将测试更改为:
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')
,那么你需要添加一个调用afterEach
的jest.resetModules
,否则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!
});