【问题标题】:TypeError when mocking request with jest用玩笑模拟请求时出现 TypeError
【发布时间】:2016-05-10 19:42:02
【问题描述】:

我对 node 比较陌生,在尝试使用 jest 模拟 request 时遇到问题。

如果我要测试的文件有require('request'),并且我尝试运行npm test,则会收到此错误:

FAIL  __tests__/sum-test.js (0.291s)
● sum › it adds 1 + 2 to equal 3
  - TypeError: The super constructor to `inherits` must have a prototype.
        at Object.exports.inherits (util.js:756:11)
        at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/private-key.js:44:6)
        at Object.<anonymous> (node_modules/request/node_modules/http-signature/node_modules/sshpk/lib/utils.js:16:18)

这是我的 package.json,如果有帮助的话:

{
  "name": "jesttest",
  "version": "1.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest-cli": "^12.0.2"
  },
  "dependencies": {
    "request": "^2.72.0"
  }
}

有人知道为什么会这样吗?

【问题讨论】:

    标签: node.js unit-testing jestjs


    【解决方案1】:

    在您的测试文件中添加jest.unmock('request')

    当您需要文件中的某些内容时,Jest 会模拟一个虚假的 require 对象。在这种情况下,请求不是真正的请求。所以告诉 jext 不要模拟请求。

    【讨论】:

    • 这对我有用。 @Manu 如果这对你有用,请接受这个作为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 1970-01-01
    • 2021-01-06
    • 2020-02-08
    相关资源
    最近更新 更多