javascript - 如何在 Jest 中模拟未安装的 npm 包?

标签 javascript jestjs

如何模拟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.resetModulesafterEach 。 ,否则 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/

相关文章:

Javascript 使用循环返回字符串中每个单词的第一个字母的位置

javascript - json数据未解析成

javascript - event.stopPropagation 停止实时事件的传播,尽管它不应该

javascript - 向 vue cli 构建添加单元测试

node.js - 如何使用 Node.js 执行集成测试?

javascript - 单击后从父函数返回

javascript - 如何从私有(private)函数访问组件范围?

javascript - Jest spyOn 不是类或对象类型的函数

typescript - 带有模块分辨率的 typescript 的 Jest 设置

javascript - 使用 Babel 转译器的 ES2015 孙子继承旁路链