![](/img/trans.png)
[英]How do I export this named function through module.exports?
[英]Why do I need `module.exports` in jest? How can I avoid it?
嘗試使用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 = ...
)僅實際需要的代碼。 此外,在這種情況下,它允許諸如笑話之類的進程訪問其他可用文件。
如果您絕對不想使用requirejs
(建議使用),則可以嘗試將它們添加到您的全局變量中,或者擺弄jests config使其在測試套件之前可用,盡管這可能比僅導出您的軟件包更困難。模組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.