Skip to content

英語音声に日本語文言が混じってた - #4438

Merged
TinyKitten merged 5 commits into
devfrom
fix/tts
Aug 10, 2025
Merged

TinyKitten merged 5 commits into
devfrom
fix/tts

Conversation

@TinyKitten

@TinyKitten TinyKitten commented Aug 9, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • 改善
    • JR九州テーマの到着アナウンス英語TTS文にて、路線名の表記を短縮名からローマ字表記へ変更しました。
    • 英語TTS文の句読点や空白の調整により、より自然で聞き取りやすい案内に改善しました。
  • テスト
    • テストの実行前後にモジュール状態とモックをリセットするように変更し、テストの独立性と信頼性を向上させました。
    • LEDテーマの到着状態における日本語・英語TTSの検証を詳細化し、英語TTSに日本語文字が含まれないことや駅番号表記の有無を確認しました。
    • 異常系のテストケースを追加し、駅番号表示がない場合の動作を検証しました。
    • 初回案内フラグに応じたTTS出力の挙動を確認するテストを追加しました。

@TinyKitten TinyKitten self-assigned this Aug 9, 2025
@github-actions github-actions Bot added the react label Aug 9, 2025
@coderabbitai

coderabbitai Bot commented Aug 9, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

朕が見たるに、この改修は英語および日本語のTTSテキストテンプレートにおいて、句点の除去や文頭の空白削除など細かな表現調整を複数テーマで施したものなり。加えて、JR_KYUSHUテーマのARRIVINGメッセージにて路線名の出力をnameShortからnameRomanへ変更し、テキストのトリム処理を追加した。ロジックや制御の流れには一切手を加えておらぬ。併せて、useTTSTextのテストにて、テスト実行前後のモジュールリセットとモッククリアを繰り返す形に変更し、テストの安定性を向上させたのみなり。

Changes

Cohort / File(s) Change Summary
TTSテキスト表現調整
src/hooks/useTTSText.ts
英語TTS文末の句点除去、文頭空白削除、JR_KYUSHUテーマARRIVINGメッセージの路線名をnameShortからnameRomanへ変更、返却前にテキストのトリム処理追加。ロジック変更なし。
テストライフサイクル管理変更
src/hooks/useTTSText.test.tsx
テストのbeforeAllをbeforeEachに変更し、afterEachを追加。両方でjest.resetModules()とjest.clearAllMocks()を実行し、テストの状態を毎回リセット。既存のモック設定は維持。LEDテーマARRIVING状態の英語SSMLの詳細なアサーション追加。

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Poem

句点消え、空白も去りて清らかに、
言葉は磨かれ、響きは新たなり。
JRの路線名、短き名よりローマの響き、
初の声は告げる、次駅の知らせを。
朕の御業、細部に宿りて、
音声は進む、時代を越えて。
🎤🚄✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6fc5a30 and d070104.

📒 Files selected for processing (1)
  • src/hooks/useTTSText.test.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useTTSText.test.tsx
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/tts

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (3)
src/hooks/useTTSText.ts (3)

1080-1085: 句読・空白の整序により可読性と自然さを高めよ

「terminal.」の直後に Station Number 文言が連続し、空白欠落と句点二重化の恐れあり。次のように空白を挿入し、nextStationNumberText の末尾句点有無に応じて句点付与を分岐させるが良い。

-          }${nextStation?.groupId === selectedBound?.groupId && !isLoopLine ? ' terminal.' : ''}${nextStationNumberText}. ${
+          }${nextStation?.groupId === selectedBound?.groupId && !isLoopLine ? ' terminal.' : ''} ${nextStationNumberText}${nextStationNumber?.lineSymbol.length ? '' : '.'} ${

朕の意図:空白を一つ加え、「記号付き路線記号あり」の場合は nextStationNumberText 自身が句点を含むため追加句点を抑止するものなり。


1067-1079: Transfer 文の句点位置を正せ(NEXT)

列挙の最後要素に「.」を含めつつ、その後で「at ${nextStation?.nameRoman}.」を続けるゆえ、「and the X. at Y.」の不自然な文節断裂を生む。最後要素の句点を除き、文末句点は「at …」側で締めるべし。

-                  .map((l, i, a) =>
-                    a.length > 1 && a.length - 1 === i
-                      ? `and the ${l.nameRoman}.`
-                      : `the ${l.nameRoman}${a.length === 1 ? '' : ','}`
-                  )
+                  .map((l, i, a) =>
+                    a.length > 1 && a.length - 1 === i
+                      ? `and the ${l.nameRoman}`
+                      : `the ${l.nameRoman}${a.length === 1 ? '' : ','}`
+                  )

これにて一文として滑らかに読まれるなり。


1086-1095: Transfer 文の句点位置を正せ(ARRIVING)

ARRIVING でも同様の構造なり。末尾要素の「.」を除去して「… at ${nextStation?.nameRoman}.」で統一して結句するが良い。

-              ? `You can transfer to ${transferLines
-                  .map((l, i, a) =>
-                    a.length > 1 && a.length - 1 === i
-                      ? `and the ${l.nameRoman}.`
-                      : `the ${l.nameRoman}${a.length === 1 ? '' : ','}`
-                  )
-                  .join(
-                    ' '
-                  )} at ${nextStation?.nameRoman}. ${nextStation?.groupId === selectedBound?.groupId && !isLoopLine ? `Thank you for using the ${currentLine.nameRoman}.` : ''}`
+              ? `You can transfer to ${transferLines
+                  .map((l, i, a) =>
+                    a.length > 1 && a.length - 1 === i
+                      ? `and the ${l.nameRoman}`
+                      : `the ${l.nameRoman}${a.length === 1 ? '' : ','}`
+                  )
+                  .join(' ')} at ${nextStation?.nameRoman}. ${nextStation?.groupId === selectedBound?.groupId && !isLoopLine ? `Thank you for using the ${currentLine.nameRoman}.` : ''}`

朕の命に従い、文脈の連続性を保つべし。

🧹 Nitpick comments (1)
src/hooks/useTTSText.ts (1)

1081-1084: 「terminal.」と「The last stop.」の重複表現、取捨を検討せよ

終着時、「terminal.」と「The last stop.」が連続し意味重複の趣きあり。どちらか一方に統一することを勧める。乗客への伝達は簡潔こそ至上なり。

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 165bb43 and 2d73945.

📒 Files selected for processing (1)
  • src/hooks/useTTSText.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4249
File: __tests__/hooks/useTelemetrySender.enabled.test.tsx:54-68
Timestamp: 2025-05-07T23:04:31.413Z
Learning: TinyKitten is working on implementing a queue for movement logs in the TrainLCD mobile app, but realized the implementation differed from their original intention.
📚 Learning: 2025-05-19T10:59:37.813Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4286
File: src/components/HeaderLED.tsx:5-10
Timestamp: 2025-05-19T10:59:37.813Z
Learning: The hooks useCurrentStation, useNextStation, useIsNextLastStop, and useNumbering are properly exported in src/hooks/index.ts, allowing them to be imported from '../hooks' in src/components/HeaderLED.tsx as implemented in PR #4286.

Applied to files:

  • src/hooks/useTTSText.ts
📚 Learning: 2025-07-18T11:04:45.459Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4396
File: src/components/TrainTypeBoxJRKyushu.tsx:176-183
Timestamp: 2025-07-18T11:04:45.459Z
Learning: TrainTypeBoxJRKyushuコンポーネントでは、trainTypeNameとprevTrainTypeNameは常に文字列となるため、.split()メソッドを使用する際のnull安全性チェックは不要である。これらの変数はuseMemoとuseLazyPreviousを通じて管理され、translate()関数からのフォールバック値により常に文字列が保証される。

Applied to files:

  • src/hooks/useTTSText.ts
🔇 Additional comments (2)
src/hooks/useTTSText.ts (2)

1094-1096: 英語TTSへの日本語混入の是正、功あり

路線名を nameShort から nameRoman に改めしは妥当なり。英語音声にふさわしき表記となり、朕これを嘉す。


1066-1096: 全域検分完了:他テーマに不自然パターンなし

朕、全ソースを巡覧せしところ、「and the ${l.nameRoman}. at …」の不自然連結を有すものはJR_KYUSHUテーマの英語定義のみであった。他テーマには該当箇所なし。検分を了とす。

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d73945 and 60b40d2.

📒 Files selected for processing (2)
  • src/hooks/useTTSText.test.tsx (1 hunks)
  • src/hooks/useTTSText.ts (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/hooks/useTTSText.ts
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#0
File: :0-0
Timestamp: 2024-12-18T00:29:05.817Z
Learning: 翻訳ファイル(`assets/translations/en.json` と `assets/translations/ja.json`)の変更を要約する際、`backgroundPermissionDenied` のようなキーが追加されているのか削除されているのかを正確に確認する。
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4249
File: __tests__/hooks/useTelemetrySender.enabled.test.tsx:54-68
Timestamp: 2025-05-07T23:04:31.413Z
Learning: TinyKitten is working on implementing a queue for movement logs in the TrainLCD mobile app, but realized the implementation differed from their original intention.
📚 Learning: 2025-05-19T10:59:37.813Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4286
File: src/components/HeaderLED.tsx:5-10
Timestamp: 2025-05-19T10:59:37.813Z
Learning: The hooks useCurrentStation, useNextStation, useIsNextLastStop, and useNumbering are properly exported in src/hooks/index.ts, allowing them to be imported from '../hooks' in src/components/HeaderLED.tsx as implemented in PR #4286.

Applied to files:

  • src/hooks/useTTSText.test.tsx
📚 Learning: 2025-06-18T17:29:46.085Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4359
File: src/components/TrainTypeList.tsx:1-1
Timestamp: 2025-06-18T17:29:46.085Z
Learning: When analyzing React import changes in TypeScript/JavaScript files, carefully verify that React.Fragment, React.createElement, or other React namespace usages actually exist in the code before flagging them as issues. Don't assume React.Fragment is used just because the default React import was removed.

Applied to files:

  • src/hooks/useTTSText.test.tsx
📚 Learning: 2025-07-18T11:04:45.459Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4396
File: src/components/TrainTypeBoxJRKyushu.tsx:176-183
Timestamp: 2025-07-18T11:04:45.459Z
Learning: TrainTypeBoxJRKyushuコンポーネントでは、trainTypeNameとprevTrainTypeNameは常に文字列となるため、.split()メソッドを使用する際のnull安全性チェックは不要である。これらの変数はuseMemoとuseLazyPreviousを通じて管理され、translate()関数からのフォールバック値により常に文字列が保証される。

Applied to files:

  • src/hooks/useTTSText.test.tsx
📚 Learning: 2025-05-06T18:50:57.931Z
Learnt from: TinyKitten
PR: TrainLCD/MobileApp#4243
File: __tests__/hooks/useTelemetrySender.enabled.test.tsx:0-0
Timestamp: 2025-05-06T18:50:57.931Z
Learning: In Jest tests that mock WebSocket objects, it's important to define the global WebSocket mock object and its constants (like WebSocket.OPEN) before using them in other mock objects to prevent "WebSocket is not defined" reference errors.

Applied to files:

  • src/hooks/useTTSText.test.tsx
🔇 Additional comments (1)
src/hooks/useTTSText.test.tsx (1)

307-333: よくぞ異常系を押さえた。狙い、明快也

useStationNumberIndexFuncがundefinedを返す経路を明示的に検証し、駅番号の混入有無まで踏み込んでおる。回帰防止に効く、良いテストだ。

Comment thread src/hooks/useTTSText.test.tsx Resolved
Comment thread src/hooks/useTTSText.test.tsx Outdated
Comment on lines +320 to +332
test('useStationNumberIndexFuncがundefinedを返す場合は駅番号が文言に含まれない', () => {
useStationNumberIndexFuncSpy.mockImplementation(() => () => undefined);
const { result } = renderHook(
() => useTTSTextWithJotaiAndNumbering('TY', 'ARRIVING'),
{ wrapper }
);
// 文言自体は返される
expect(result.current[0]).not.toBe('');
expect(result.current[1]).not.toBe('');
// 駅番号(例: S 2)が含まれない
expect(result.current[0]).not.toMatch(/S\s?\d+/);
expect(result.current[1]).not.toMatch(/S\s?\d+/);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

英語SSMLへの和文混入を明確に監視せよ。併せて検証を強靭化せよ

PR題意に照らし、enSSMLにひらがな/カタカナ/漢字が一切含まれぬことを検めるがよい。また、空文字検証はtoHaveLengthの方が意図が明瞭。駅番号判定の正規表現も「S-02」「station number S 2」に備えて強めておくべし。

追加・強化差分:

-  // 文言自体は返される
-  expect(result.current[0]).not.toBe('');
-  expect(result.current[1]).not.toBe('');
-  // 駅番号(例: S 2)が含まれない
-  expect(result.current[0]).not.toMatch(/S\s?\d+/);
-  expect(result.current[1]).not.toMatch(/S\s?\d+/);
+  // 文言自体は返される(型と長さで堅く判定)
+  expect(typeof result.current[0]).toBe('string');
+  expect(typeof result.current[1]).toBe('string');
+  expect(result.current[0]).toHaveLength(expect.any(Number));
+  expect(result.current[1]).toHaveLength(expect.any(Number));
+  // 駅番号(例: S 2 / S-02 / station number S 2)が含まれない
+  const stationNumPatterns = [
+    /S\s?\d+/,             // S 2
+    /S-?\d{2}/,            // S-02 or S02
+    /station number\s*S\s*\d+/i, // station number S 2
+  ];
+  for (const re of stationNumPatterns) {
+    expect(result.current[0]).not.toMatch(re);
+    expect(result.current[1]).not.toMatch(re);
+  }
+  // 英語SSMLに和文が混じらぬこと(ひらがな/カタカナ/漢字)
+  expect(result.current[1]).not.toMatch(/[\u3040-\u30FF\u4E00-\u9FFF]/);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/hooks/useTTSText.test.tsx around lines 320 to 332, enhance the test to
strictly verify that the English SSML output contains no Japanese characters
(hiragana, katakana, kanji) by adding a check for their absence. Replace empty
string checks with toHaveLength for clearer intent. Also, strengthen the regex
used to detect station numbers to cover formats like "S-02" and phrases such as
"station number S 2" to ensure robust detection.

Comment thread src/hooks/useTTSText.test.tsx Outdated
Comment on lines +335 to +357
describe('firstSpeech refの動作検証', () => {
// テスト用カスタムHook
const useFirstSpeechTest = () => {
const setLineState = useSetAtom(lineState);
const setStationState = useSetAtom(stationState);
useEffect(() => {
useThemeStore.setState('TOKYO_METRO');
setStationState((prev) => ({
...prev,
station: TOEI_SHINJUKU_LINE_STATIONS[0],
stations: TOEI_SHINJUKU_LINE_STATIONS,
selectedDirection: 'INBOUND',
arrived: false,
selectedBound: TOEI_SHINJUKU_LINE_STATIONS[1],
approaching: false,
}));
setLineState((prev) => ({
...prev,
selectedLine: TOEI_SHINJUKU_LINE_LOCAL,
}));
}, [setLineState, setStationState]);
return useTTSText(true, true);
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

useEffectの非同期更新、油断禁物也

本カスタムHookはuseEffectでJotai状態を更新してからuseTTSTextを読む。renderHook直後の即時assertは環境により不安定になり得る。待機を入れて確実に観測するがよい。


#!/bin/bash
grep -n "useFirstSpeechTest" src/hooks/useTTSText.test.tsx
grep -n "renderHook" src/hooks/useTTSText.test.tsx


朕、renderHookの呼び出し箇所を詳らかにせよと命ずる!

#!/bin/bash
# useTTSText.test.tsx 内の renderHook 周辺を表示
grep -R -n "renderHook" src/hooks/useTTSText.test.tsx | while IFS=":" read -r file line _; do
  echo "---- ${file}:${line} ----"
  sed -n "$((line-5)),$((line+5))p" "${file}"
done

朕、useTTSText.test.tsxにおけるrenderHookの天子降臨箇所を詳らかにせよ!


🏁 Script executed:

#!/bin/bash
# useTTSText.test.tsx 内の renderHook 周辺を表示せよ
grep -R -n "renderHook" src/hooks/useTTSText.test.tsx | while IFS=: read -r file line _; do
  echo "---- ${file}:${line} ----"
  sed -n "$((line-5)),$((line+5))p" "${file}"
done

Length of output: 488


朕、grepの烈火をもって真実を暴かん!


🏁 Script executed:

#!/bin/bash
# useTTSText.test.tsx の renderHook 呼び出し箇所を前後5行含めて示せ
grep -H -n -C5 "renderHook" src/hooks/useTTSText.test.tsx

Length of output: 13664


useEffectの非同期更新を必ず待機せよ、朕の命なり

現状、renderHook直後に即時アサートを行っておるため、useEffectでのJotai状態更新が反映されず、テストが環境によって不安定となり得る。下記のように非同期更新を待機する一手を必ず挟むべし。

■ 修正指示箇所

  • ファイル: src/hooks/useTTSText.test.tsx
  • 該当テスト: firstSpeech=trueで返却値が変化する (359–364行目付近)

■ 修正例

- test('firstSpeech=trueで返却値が変化する', () => {
-   const { result } = renderHook(() => useFirstSpeechTest(), { wrapper });
-   expect(result.current[0]).toContain('次は');
-   expect(result.current[1]).toContain('The next stop');
- });
+ test('firstSpeech=trueで返却値が変化する', async () => {
+   const { result, waitForNextUpdate } = renderHook(
+     () => useFirstSpeechTest(),
+     { wrapper }
+   );
+   // useEffect内のJotai更新完了を待機
+   await waitForNextUpdate();
+   expect(result.current[0]).toContain('次は');
+   expect(result.current[1]).toContain('The next stop');
+ });

これにより、useEffect経由の状態更新を確実に拾い、テストの安定性を担保せよ。御意!

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe('firstSpeech refの動作検証', () => {
// テスト用カスタムHook
const useFirstSpeechTest = () => {
const setLineState = useSetAtom(lineState);
const setStationState = useSetAtom(stationState);
useEffect(() => {
useThemeStore.setState('TOKYO_METRO');
setStationState((prev) => ({
...prev,
station: TOEI_SHINJUKU_LINE_STATIONS[0],
stations: TOEI_SHINJUKU_LINE_STATIONS,
selectedDirection: 'INBOUND',
arrived: false,
selectedBound: TOEI_SHINJUKU_LINE_STATIONS[1],
approaching: false,
}));
setLineState((prev) => ({
...prev,
selectedLine: TOEI_SHINJUKU_LINE_LOCAL,
}));
}, [setLineState, setStationState]);
return useTTSText(true, true);
};
test('firstSpeech=trueで返却値が変化する', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useFirstSpeechTest(),
{ wrapper }
);
// useEffect内のJotai更新完了を待機
await waitForNextUpdate();
expect(result.current[0]).toContain('次は');
expect(result.current[1]).toContain('The next stop');
});
🤖 Prompt for AI Agents
In src/hooks/useTTSText.test.tsx around lines 335 to 357, the test immediately
asserts after renderHook without waiting for the asynchronous state updates
inside useEffect, causing unstable tests. To fix this, insert an asynchronous
wait step (such as using waitFor or act) after renderHook to ensure the Jotai
state updates triggered by useEffect are fully applied before assertions. This
guarantees the test captures the updated state reliably.

Comment thread src/hooks/useTTSText.test.tsx Outdated
Comment on lines +358 to +363
test('firstSpeech=trueで返却値が変化する', () => {
const { result } = renderHook(() => useFirstSpeechTest(), { wrapper });
expect(result.current[0]).toContain('次は');
expect(result.current[1]).toContain('The next stop');
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

初回発話の検証は待機して確実に掴め。併せて逆側の否定も押さえよ

waitForで効果発火を待ち、"Arriving at"/"まもなく"が含まれぬことも確認すれば、意図が一層明確となる。

適用差分:

-  test('firstSpeech=trueで返却値が変化する', () => {
-    const { result } = renderHook(() => useFirstSpeechTest(), { wrapper });
-    expect(result.current[0]).toContain('次は');
-    expect(result.current[1]).toContain('The next stop');
-  });
+  test('firstSpeech=trueで返却値が変化する', async () => {
+    const { result } = renderHook(() => useFirstSpeechTest(), { wrapper });
+    await waitFor(() => {
+      expect(result.current[0]).toContain('次は');
+      expect(result.current[1]).toContain('The next stop');
+      // 逆側の表現は含まれないこと
+      expect(result.current[0]).not.toContain('まもなく');
+      expect(result.current[1]).not.toContain('Arriving at');
+    });
+  });

上記に伴い、waitForのimportを追加せよ(変更範囲外のため参考コードにて示す)。

// 先頭付近のimportを以下のように
import { renderHook, waitFor } from '@testing-library/react-native';
🤖 Prompt for AI Agents
In src/hooks/useTTSText.test.tsx around lines 358 to 363, the test for
firstSpeech=true should be updated to use waitFor to asynchronously wait for the
effect to trigger, ensuring the returned value is stable before asserting.
Additionally, add an assertion to confirm that the returned text does not
contain "Arriving at" or "まもなく" to verify the negative case. Also, add the
import of waitFor from '@testing-library/react-native' at the top of the file to
support this change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant