質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

841閲覧

ReactTestUtilsを使ったイベント処理のテストが期待通りの結果になりません。

退会済みユーザー

退会済みユーザー

総合スコア0

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2020/05/11 05:35

困っていること

以下のテストが通りません。
参考: React開発 現場の教科書(本)

ソースコードです。

test("onClickFunction", () => { const props = { background: "red", color: "white", text: "hoge", onClickFunction: jest.fn(), }; const instance = ReactTestUtils.renderIntoDocument( <div> <Btn {...props} /> </div> ); const node = ReactDOM.findDOMNode(instance); ReactTestUtils.Simulate.click(node); expect(props.onClickFunction).toBeCalled(); });
● onClickFunction expect(jest.fn()).toBeCalled() Expected number of calls: >= 1 Received number of calls: 0
import * as React from "react"; import styled from "styled-components"; interface 略 const BtnStyled 略 const Btn: React.FC<Props> = ({ background, color, onClickFunction, text }) => { return ( <BtnStyled color={color} background={background} onClick={onClickFunction}> {text} </BtnStyled> ); }; export default Btn;

関係なさそうな部分は省略しました。必要な箇所があれば教えてください。
また、より良いコンポーネントのテスト方法(ベストプラクティス?)があれば教えてください

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

enzyme(とenzyme-adapter-react-16)を導入して以下のようにソースコードを変更したらテストが通りました。

import React from "react"; import ReactDOM from "react-dom"; import ReactTestUtils from "react-dom/test-utils"; import { configure, mount } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; configure({ adapter: new Adapter() }); import Btn from "../../web/src/components/atoms/Btn"; test("onClickFunction", () => { const props = { background: "red", color: "white", text: "hoge", onClickFunction: jest.fn(), }; const subject = mount(<Btn {...props} />); subject.find("button").simulate("click"); expect(props.onClickFunction).toBeCalled(); });
  • mountは当初、shallow()だったのですがテストが通りませんでした。

投稿2020/05/11 10:07

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問