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

93 lines
2.6 KiB
TypeScript
Raw Permalink Normal View History

2023-03-18 15:54:29 +02:00
// Copyright (c) 2023 Tudor Stanciu
2023-02-12 01:53:42 +02:00
import React from "react";
import { renderHook } from "@testing-library/react-hooks";
import { TuitioContext, TuitioDispatchContext } from "../../src/contexts";
import { useTuitioClient } from "../../src/hooks";
const userName = "tuitio.user";
const token = "mocked-token";
const expiresIn = 600000;
2023-02-12 01:53:42 +02:00
jest.mock("@flare/tuitio-client", () => ({
TuitioClient: jest.fn().mockImplementation(() => ({
login: jest.fn().mockResolvedValue({
result: { token, expiresIn, validUntil: new Date() },
error: null
}),
logout: jest.fn().mockResolvedValue({
result: { userId: 0, userName, logoutDate: new Date() },
error: null
2023-02-12 01:53:42 +02:00
})
})),
fetch: jest.fn().mockResolvedValue({
token,
validUntil: new Date(),
userName
2023-02-12 01:53:42 +02:00
})
}));
describe("useTuitioClient: dispatchActions", () => {
let spyOnLoginSuccess: (token: string, validUntil: Date, userName: string) => void;
let spyOnLogoutSuccess: () => void;
2023-02-12 01:53:42 +02:00
beforeEach(() => {
spyOnLoginSuccess = jest.fn();
spyOnLogoutSuccess = jest.fn();
2023-02-12 01:53:42 +02:00
});
afterEach(() => {
(spyOnLoginSuccess as jest.Mock).mockReset();
(spyOnLogoutSuccess as jest.Mock).mockReset();
2023-02-12 01:53:42 +02:00
});
const tuitioContextState = {
2023-03-18 02:29:06 +02:00
auth: {
userName: "",
token: "mocked-token",
validUntil: new Date()
},
2023-02-12 01:53:42 +02:00
configuration: { tuitioUrl: null }
};
type Props = {
children: React.ReactNode;
};
const wrapper = ({ children }: Props) => (
<TuitioContext.Provider value={tuitioContextState}>
<TuitioDispatchContext.Provider
value={{
onLoginSuccess: spyOnLoginSuccess,
onLogoutSuccess: spyOnLogoutSuccess,
onUserInfoLoaded: jest.fn()
}}
>
2023-02-12 01:53:42 +02:00
{children}
</TuitioDispatchContext.Provider>
</TuitioContext.Provider>
);
2023-03-18 15:54:29 +02:00
const optionsMock = {
2023-02-12 01:53:42 +02:00
onLoginSuccess: jest.fn(),
onLoginFailed: jest.fn(),
onLoginError: jest.fn()
};
it("onLoginSuccess should be called when user logs in", async () => {
2023-03-18 15:54:29 +02:00
const { result } = renderHook(() => useTuitioClient(optionsMock), { wrapper });
2023-02-12 01:53:42 +02:00
const userName = "user";
const password = "password";
const response = await result.current.login(userName, password);
expect(spyOnLoginSuccess).toHaveBeenCalledWith(response.result?.token, response.result?.validUntil, userName);
2023-02-12 01:53:42 +02:00
});
it("onLogoutSuccess should be called when user logs out", async () => {
2023-03-18 15:54:29 +02:00
const { result } = renderHook(() => useTuitioClient(optionsMock), { wrapper });
await result.current.logout();
expect(spyOnLogoutSuccess).toHaveBeenCalled();
2023-02-12 01:53:42 +02:00
});
});