将 web3.js 与 Jest 一起使用时出错

Posted

技术标签:

【中文标题】将 web3.js 与 Jest 一起使用时出错【英文标题】:Error when using web3.js with Jest 【发布时间】:2018-03-22 04:52:01 【问题描述】:

当我运行以下使用 web3.js 包的 Jest 测试时

const Web3 = require("web3");

test("Web3 version", function()

    expect(Web3.version).toEqual("1.0.0-beta.23");
);

我收到以下错误

Cannot find module './build/Release/scrypt' from 'index.js'

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:191:17)

web3 似乎安装正确,因为以下正确输出 Web3 version = 1.0.0-beta.23

const Web3 = require("web3");

console.log("Web3 version = " + Web3.version);

我是 Jest 的新手(今天第一次使用它)所以我不确定问题是我的 Jest 安装/设置还是 web3.js。

我在 GitHub 上创建了一个简单的项目来复制问题 https://github.com/naddison36/web3-jest

我的机器正在运行 Mac OS X 10.12.6、节点 v6.10.3 和 npm 3.10.10。 测试项目使用web3.js版本1.0.0-beta.23和Jest21.2.1

【问题讨论】:

【参考方案1】:

在你的 package.json 中添加“node”到 jest -> moduleFileExtensions 应该可以修复它。

... "jest": "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", "moduleFileExtensions": [ "ts", "tsx", "js", "jsx", "json", "node" ]

参考:https://facebook.github.io/jest/docs/en/configuration.html#modulefileextensions-array-string

【讨论】:

谢谢。将“node”添加到“moduleFileExtensions”就可以了! @naddison 如果您觉得它有用,您能否将答案添加为已接受的答案? ;) @Ronin 让我知道如何提供帮助。如果您可以提供更多详细信息。 对我不起作用,这是错误:These options in your package.json Jest configuration are not currently supported by Create React App: • testRegex • moduleFileExtensions【参考方案2】:

作为一种解决方法,将此行 require("./build/Release/scrypt") 更改为 require("scrypt") 从 '/node_modules/scrypt/index.js'

【讨论】:

以上是关于将 web3.js 与 Jest 一起使用时出错的主要内容,如果未能解决你的问题,请参考以下文章

将 jest 与 web3 和 ganache 一起使用时测试很慢

将 Jest 与 Nuxt 组件一起使用时无法读取未定义的属性 $loading

将 React/Enzyme/Jest 与 Nextjs 一起使用时是不是可以获得整页 html?

如何使用 Typescript 将 jest.spyOn 与 React 函数组件一起使用

Web3.js1.0与智能合约交互

将码头与 Repast simphony 一起使用时出错