如何在jest中模拟未安装的npm包?

问题描述 投票:1回答:1

如何在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 - >不会起作用,因为我猜测试是在不同的过程中运行的。

javascript jestjs
1个回答
1
投票

当您在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'),那么你需要添加一个调用afterEachjest.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!
});
© www.soinside.com 2019 - 2024. All rights reserved.