2015-07-22 31 views
3

我有較高階分量嘲笑高階函數:陣營TestUtils不與裝飾工作或如何使用重新佈線

import React from 'react'; 

function withMUI(ComposedComponent) { 
    return class withMUI { 
    render() { 
     return <ComposedComponent {...this.props}/>; 
    } 
    }; 
} 

,並且組件:

@withMUI 
class PlayerProfile extends React.Component { 
    render() { 
    const { name, avatar } = this.props; 
    return (
     <div className="player-profile"> 
     <div className='profile-name'>{name}</div> 
     <div> 
      <Avatar src={avatar}/> 
     </div> 
     </div> 
    ); 
    } 
} 

和(通過)測試使用React.findDOMNode

describe('PlayerProfile',() => { 
    // profile is type of `withMUI` 
    let profile = TestUtils.renderIntoDocument(<OkeyPlayerProfile/>); 

    it('should work',() => { 
    let elem = React.findDOMNode(profile); 

    // logs successfully 
    console.log(elem.querySelectorAll('.player-profile')); 
    }); 

    // ... 
}); 

和使用TestUtils另一個(失敗)測試:

// ... 
    it('should also work',() => { 
    let elem = TestUtils.findComponentWithTag(profile, 'div'); 
    // throws can't find a match 
    console.log(elem); 
    }); 

如果我刪除了@withMUI裝飾器,它按預期工作。那麼爲什麼裝飾效果TestUtils.findComponentWithTag,我該如何做這項工作?

我該如何模擬withMUI函數?使用babel-plugin-rewire。或重新接線?

+0

當我用'findComponentWithTag',我記得它返回所有的M無論深度如何。如果這對你來說是一樣的話,我會期待3個匹配的'div'和一個錯誤響應。如果您使用'scryComponentsWithTag',它將返回一個包含所有匹配項的數組。數組的長度是0還是3? –

+0

它是0 @JeffFairley,但是如果我不使用'withMUI',則它是3。 – eguneys

+0

K.謝謝。只是不得不問。 –

回答

2

你可以用「通天-插件 - 刪除 - 裝飾」插件

首先安裝插件,然後創建一個具有以下內容的文件,讓我們把它叫做「babelTestingHook.js」

require('babel/register')({ 
'stage': 2, 
'optional': [ 
    'es7.classProperties', 
    'es7.decorators', 
    // or Whatever configs you have 
    ..... 
], 
'plugins': ['babel-plugin-remove-decorators:before'] 
}); 

和運行測試,如下面將忽略的裝飾,你將能夠測試組件通常

mocha ./tests/**/*.spec.js --require ./babelTestingHook.js --recursive