gpt4 book ai didi

javascript - 为什么我需要 `module.exports` 开 Jest ?我怎样才能避免它?

转载 作者:行者123 更新时间:2023-12-03 09:32:01 25 4
gpt4 key购买 nike

我在尝试使用 jest 框架测试我的 React js 代码时遇到了麻烦。

假设这是我的组件:

# 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>

所以,我想使用 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

我遇到了麻烦:

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

如果我将 module.exports = @GlobalWidget 附加到 coffee/global_widget.coffee,那么我会得到TerminalWidget is not Defined。什么是 module.exports= 以及为什么我需要将它们放入代码中的每个组件?

最佳答案

看起来 jest 无法访问您的全局变量,因此您需要导出每个文件并根据需要需要它们。
您需要使用 module.exports,因为您在这行 GlobalWidget = require('../coffee/global_widget') 中使用了 requirejs 语法。这样做的目的是隔离您的代码,以防止出现一堆全局可用的代码。这样,您就可以仅导入(使用 require)和导出(使用 module.exports = ...)您实际需要的代码。此外,在本例中,它允许 jest 等进程访问原本可用的文件。

如果你绝对不想使用 requirejs (建议使用),你可以尝试将它们添加到你的全局变量中或摆弄 Jest config在您的测试套件之前使这些可用,尽管这可能比仅仅导出模块更困难

关于javascript - 为什么我需要 `module.exports` 开 Jest ?我怎样才能避免它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com