简体   繁体   English

为什么在玩笑中需要`module.exports`? 我该如何避免呢?

[英]Why do I need `module.exports` in jest? How can I avoid it?

I've met the trouble when trying to test my react js code using jest framework. 尝试使用jest框架测试我的react js代码时遇到了麻烦。

Let say this is mine component: 可以说这是我的组成部分:

# coffee/global_widget.coffee
@GlobalWidget = React.createClass
  render: ->
    <div className='row'>
      <div className='col-md-12'>
        <TerminalWidget />
      </div>
    </div>

# coffee/terminal_widget.coffee
@TerminalWidget = React.createClass
  render: ->
    <div>Hey! This is the terminal!</div>

So, I want to test it using jest . 因此,我想使用jest进行测试。

jest.dontMock '../coffee/global_widget'

describe 'GlobalWidget', ->
  global.React = require('react/addons')
  GlobalWidget = require('../coffee/global_widget')
  TestUtils = React.addons.TestUtils

  globalWidgetForTest = TestUtils.renderIntoDocument(<GlobalWidget />)
  # body of the test

I have a trouble: 我有麻烦:

npm test

> terminal-ui@0.0.2 test /home/alex/my_project
> jest

Using Jest CLI v0.4.5
 FAIL  __tests__/global_widget-test.coffee (0.276s)
● GlobalWidget › it encountered a declaration exception
  - ReferenceError: GlobalWidget is not defined

If I append module.exports = @GlobalWidget to the coffee/global_widget.coffee , then I get TerminalWidget is not defined . 如果我将module.exports = @GlobalWidget附加到coffee/global_widget.coffee ,那么我得到的TerminalWidget is not defined What is module.exports= and why do I need to puts them for every component in my code? 什么是module.exports= ?为什么我需要在代码中将其放入每个组件?

It looks like jest doesnt have access to your global variables, so you need to export each file and require them as necessary. 看起来jest无法访问您的全局变量,因此您需要导出每个文件,并在需要时需要它们。
you need to use module.exports because youre using the requirejs syntax with this line GlobalWidget = require('../coffee/global_widget') . 您需要使用module.exports,因为您在这行GlobalWidget = require('../coffee/global_widget')使用了requirejs语法。 What this does is isolate your code to prevent having a bunch of globally available code. 这样做是隔离您的代码,以防止拥有一堆全局可用的代码。 this way, you import (using require ) and export (using module.exports = ... ) only the code you actually need. 这样,您仅导入(使用require )和导出(使用module.exports = ... )仅实际需要的代码。 additionally, as in this case, it allows processes such as jest to gain access to files that are otherwise available. 此外,在这种情况下,它允许诸如笑话之类的进程访问其他可用文件。

if you absolutely dont want to use requirejs (which would be recommended to use) you can try adding them to your globals or fiddling with jests config to make these available prior to your test suite, though this will probably be more difficult than just exporting your modules 如果您绝对不想使用requirejs (建议使用),则可以尝试将它们添加到您的全局变量中,或者摆弄jests config使其在测试套件之前可用,尽管这可能比仅导出您的软件包更困难。模组

如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 module.exports 导出这个名为 function 的文件? - How do I export this named function through module.exports? 如何在节点 js 中使用 module.exports 导出数组? - How do I export an array with module.exports in node js? 尝试将中间件功能导出到module.exports对象时,为什么会得到“下一个不是功能”的信息? - Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object? 回复:如何将javascript AMD模块导入外部TypeScript模块? (使用module.exports =…时) - Re: How can I import a javascript AMD module into an external TypeScript module? (When using module.exports=…) 我没有从module.exports得到答案 - I do not get an answer from module.exports 如何在我的 index.js / discord.js 中传递 module.exports - How do I pass module.exports in my index.js / discord.js 如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports? 如何在 node.js 的`module.exports = class` 中创建静态变量 - How can I make static variable in `module.exports = class` in node.js 如何在设置module.exports之前等待异步功能完成 - How can I wait for asyncronous functions to complete before setting module.exports 如何使 typescript 导出与 module.exports 向后兼容 - How can I make typescript export backward compatible with module.exports
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM