1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】jestのテストでProviderが機能しない症状の解決方法について

Posted at

はじめに

jestのテストでログイン中にログインボタンが表示されないテストを実装するところでつまずいたので記事にします。

下記のようなエラーでログインボタンが取得されている状態でした。

TestingLibraryElementError: Unable to find an accessible element with the role "button" and name "ログイン"

【修正前のコード】

.tsx

beforeEach(async () => {
  render (
    <BrowserRouter>
      <Home />
    </BrowserRouter>
  );
});


//////////その他テスト/////////////////////////



it("ログアウトボタンを押すとログインボタンが表示されていること", async () => {
    const store = createStore();
    store.set(loginAtom, true);

    render(
      <Provider store={store}>
        <BrowserRouter>
          <Home />
        </BrowserRouter>
      </Provider>
    );

    const logoutButton = screen.getByRole("button", { name: "ログアウト" });
    userEvent.click(logoutButton);
    store.set(loginAtom, false);
    await waitFor(() => {
      expect(screen.getByRole("button", { name: "ログイン" })).toBeInTheDocument();
    });
  });

解決方法

beforeEach内のrender削除

参考

おわりに

他のテストで使用していたbeforeEach内のrenderによって、実行させたいtest時にrender内のコンポーネントが混在しているような状態になっていました。


1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?