How to test decorated React component with shallow rendering

后端 未结 5 968
旧巷少年郎
旧巷少年郎 2020-12-15 19:45

I am following this tutorial: http://reactkungfu.com/2015/07/approaches-to-testing-react-components-an-overview/

Trying to learn how \"shallow rendering\" works.

5条回答
  •  -上瘾入骨i
    2020-12-15 20:28

    You can't. First let's slightly desugar the decorator:

    let PlayerProfile = withMUI(
        class PlayerProfile extends React.Component {
          // ...
        }
    );
    

    withMUI returns a different class, so the PlayerProfile class only exists in withMUI's closure.

    This is here's a simplified version:

    var withMUI = function(arg){ return null };
    var PlayerProfile = withMUI({functionIWantToTest: ...});
    

    You pass the value to the function, it doesn't give it back, you don't have the value.

    The solution? Hold a reference to it.

    // no decorator here
    class PlayerProfile extends React.Component {
      // ...
    }
    

    Then we can export both the wrapped and unwrapped versions of the component:

    // this must be after the class is declared, unfortunately
    export default withMUI(PlayerProfile);
    export let undecorated = PlayerProfile;
    

    The normal code using this component doesn't change, but your tests will use this:

    import {undecorated as PlayerProfile} from '../src/PlayerProfile';
    

    The alternative is to mock the withMUI function to be (x) => x (the identity function). This may cause weird side effects and needs to be done from the testing side, so your tests and source could fall out of sync as decorators are added.

    Not using decorators seems like the safe option here.

提交回复
热议问题