6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Reactをjestでテストするとき、material-uiを利用しているComponentでmuiThemeが無いと怒られるのを回避する

Last updated at Posted at 2017-06-14

タイトルのままですが、jest実行時に、親のComponentからMuiThemeProviderを設定しており、子のComponent内部でmaterial-uiのComponentを利用していると

some_parent_component.jsx
  ...
  render(){
    return(
      <MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
        <Router>
          <BaseRouter />
        </Router>
      </MuiThemeProvider>
    )
  }

  ● Console

    console.error node_modules/fbjs/lib/warning.js:36
      Warning: Failed context type: The context `muiTheme` is marked as required in `CircularProgress`, but its value is `undefined`.
          in CircularProgress (created by Issue)
          in div (created by Issue)
          in withScriptjs(withGoogleMap(Component)) (created by Issue)
          in div (created by Issue)
          in Issue

  ● Issue component › renders component

    TypeError: Cannot read property 'prepareStyles' of undefined

      at CircularProgress.render (node_modules/material-ui/CircularProgress/CircularProgress.js:187:48)
      at node_modules/react-dom/lib/ReactCompositeComponent.js:796:21

こんな感じでThe context muiTheme is marked as requiredとかCannot read property 'prepareStyles' of undefinedと怒られてしまいます。
ここは親のComponentから与えているので出来たらテストでは無視してもらいたい(でないと全てのComponentを<MuiThemeProvider>でwrapするハメになるので)のですが、そうなってません。

回避する方法としては、テスト内で

some_component_test.js
    const wrapper = render(
      <SomeComponent />,
      {
        context: {
          muiTheme: getMuiTheme(),
        },
        childContextTypes: {
          muiTheme: PropTypes.object.isRequired,
        }
      }
    )

として、render(とかmount)時の引数にcontext等を設定してやればOKです。
テスト内の記述が増えるのでちょっと微妙な感じではあるので、ベターな回避方法があれば知りたい所です。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?