tuitio-client-react/tests/hooks/useTuitioClient.test.ts

114 lines
2.8 KiB
TypeScript

import { renderHook, act } from "@testing-library/react-hooks";
import { TuitioClient, invalidate } from "@flare/tuitio-client";
import { useTuitioClient } from "../../src/hooks";
jest.mock("@flare/tuitio-client", () => ({
TuitioClient: jest.fn().mockImplementation(() => ({
authenticate: jest.fn().mockResolvedValue({
token: {
raw: "mocked-token",
validFrom: new Date(),
validUntil: new Date()
},
status: "success"
})
})),
invalidate: jest.fn(),
fetch: jest.fn().mockResolvedValue({
token: {
raw: "mocked-token",
validFrom: new Date(),
validUntil: new Date()
},
userName: "user"
})
}));
describe("useTuitioClient", () => {
it("should call onLoginSuccess when login is successful", async () => {
const onLoginSuccess = jest.fn();
const { result } = renderHook(() =>
useTuitioClient({
onLoginSuccess,
onLoginFailed: jest.fn(),
onLoginError: jest.fn()
})
);
await act(async () => {
await result.current.login("user", "password");
});
expect(onLoginSuccess).toHaveBeenCalledWith(
{
token: {
raw: "mocked-token",
validFrom: expect.any(Date),
validUntil: expect.any(Date)
},
status: "success"
},
"user"
);
});
it("should call onLoginFailed when login is unsuccessful", async () => {
const onLoginFailed = jest.fn();
(TuitioClient as jest.Mocked<any>).mockImplementation(() => ({
authenticate: jest.fn().mockResolvedValue({
token: null,
status: "failed"
})
}));
const { result } = renderHook(() =>
useTuitioClient({
onLoginSuccess: jest.fn(),
onLoginFailed,
onLoginError: jest.fn()
})
);
await act(async () => {
await result.current.login("user", "password");
});
expect(onLoginFailed).toHaveBeenCalledWith(
{
token: null,
status: "failed"
},
"user"
);
});
it("should call onLoginError with error if authentication fails", async () => {
(TuitioClient as jest.Mocked<any>).mockImplementation(() => ({
authenticate: jest.fn().mockRejectedValue(new Error("Login failed"))
}));
const onLoginError = jest.fn();
const { result } = renderHook(() =>
useTuitioClient({ onLoginSuccess: jest.fn(), onLoginFailed: jest.fn(), onLoginError })
);
await act(async () => {
try {
await result.current.login("user", "password");
} catch (error) {
expect(onLoginError).toHaveBeenCalledWith(error);
}
});
});
it("should call invalidate when logout is called", () => {
const { result } = renderHook(() => useTuitioClient());
act(() => {
result.current.logout();
});
expect(invalidate).toHaveBeenCalled();
});
});