/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ import React from "react"; import { render, act, screen, within } from "@testing-library/react"; import { useCurrentAuthenticatedUser, useUsers } from "../user-hooks"; import BackendService from "../../services/BackendService"; import { Auth } from "@aws-amplify/auth"; describe("useCurrentAuthenticatedUser", () => { const FooComponent = () => { const { username, isFederatedId, hasRole } = useCurrentAuthenticatedUser(); return ( <> {username} {`${isFederatedId}`} {`${hasRole}`} ); }; test("should fetch the authenticated user", async () => { const sampleUser: any = { username: "cognito user", attributes: { identities: '[{ "providerType": "Federated" }]', "custom:roles": "Admin", }, }; const currentAuthenticatedUserSpy = jest .spyOn(Auth, "currentAuthenticatedUser") .mockImplementation(() => Promise.resolve(sampleUser)); await act(async () => { render(); }); expect(currentAuthenticatedUserSpy).toHaveBeenCalled(); expect( within(screen.getByTestId("username")).getByText(sampleUser.username), ).toBeInTheDocument(); expect(within(screen.getByTestId("isFederatedId")).getByText("true")).toBeInTheDocument(); expect(within(screen.getByTestId("hasRole")).getByText("true")).toBeInTheDocument(); }); }); describe("useUsers", () => { const FooComponent = () => { const { users } = useUsers(); return ( <> {users?.length} ); }; test("should fetch the users", async () => { const fetchUsersSpy = jest .spyOn(BackendService, "fetchUsers") .mockImplementation(() => Promise.resolve([])); await act(async () => { render(); }); expect(fetchUsersSpy).toHaveBeenCalled(); expect(screen.getByText(0)).toBeInTheDocument(); }); });