[英]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使其在测试套件之前可用,尽管这可能比仅导出您的软件包更困难。模组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.