💻

Fluent UI の Menu をテストすると FocusZone が謎のエラーを発生させる

2022/01/01に公開

事象

こんな感じのコードがあったとします。

import React from 'react';
import { Menu } from '@fluentui/react-northstar';
import './App.css';

const App: React.FC = () => {

  return (
    <div>
      <Menu
        items={[
          {
            key: 'hop',
            content: 'Hop'
          },
          {
            key: 'step',
            content: 'Step'
          },
          {
            key: 'jump',
            content: 'Jump'
          }
        ]}
      />
    </div>
  );
}

export default App;

これに対してスナップショット テストを実行してみます。

import React from 'react';
import App from './App';
import renderer from 'react-test-renderer';

describe('App', () => {

  it('renders correctly', () => {
    const tree = renderer
      .create(<App />)
      .toJSON();
    expect(tree).toMatchSnapshot();
  });

});

コードは Jest のドキュメントを参考にしています。

https://jestjs.io/ja/docs/snapshot-testing

ところがこれを実行するとエラーになります。

console.error
  The above error occurred in the <FocusZone> component:
      in FocusZone (created by Menu)
      in Menu (created by App)
      in div (created by App)
      in App

  Consider adding an error boundary to your tree to customize error handling behavior.
  Visit https://fb.me/react-error-boundaries to learn more about error boundaries.

    at logCapturedError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10141:21)
    at logError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10178:5)
    at update.callback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11288:5)
    at callCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3259:12)
    at commitUpdateQueue (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3280:9)
    at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10497:11)
    at commitLayoutEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13295:7)

回避策

react-test-renderer じゃなくて Testing Library を使いましょう。

import React from 'react';
import App from './App';
import { render } from '@testing-library/react';

describe('App', () => {

  it('renders correctly', () => {
    const { container } = render(<App />);
    expect(container).toMatchSnapshot();
  });

});

Discussion