tuitio-client/src/__tests__/TuitioAuthentication.test.ts

69 lines
1.9 KiB
TypeScript

/**
* @jest-environment jsdom
*/
import axios from "axios";
import { TuitioClient, fetch, invalidate } from "../client";
jest.mock("axios");
test("Tuitio client authentication", async () => {
(axios.request as jest.Mock).mockResolvedValue({
data: {
token: { raw: "mock-user-pass", validFrom: new Date("10/02/2023"), validUntil: new Date("11/02/2023") },
status: "_MOCK_"
}
});
const client = new TuitioClient("https://test.com/api");
const result = await client.authenticate("user", "pass");
expect(result.token.raw).toBe("mock-user-pass");
expect(result.token.validFrom).toStrictEqual(new Date("10/02/2023"));
expect(result.token.validUntil).toStrictEqual(new Date("11/02/2023"));
expect(result.status).toBe("_MOCK_");
const storage = fetch();
expect(storage.userName).toBe("user");
invalidate();
const emptyStorage = fetch();
expect(emptyStorage.userName).toBeNull();
});
test("Tuitio client failed authentication", async () => {
(axios.request as jest.Mock).mockRejectedValueOnce({
response: {
status: 500,
data: { title: "Internal server error" }
}
});
const client = new TuitioClient("https://test.com/api");
try {
await client.authenticate("user", "pass");
} catch (error: any) {
expect(error.title).toBe("Internal server error");
expect(error.message).toBe("Internal server error");
}
});
test("Tuitio client failed authentication with unhandled exception", async () => {
(axios.request as jest.Mock).mockRejectedValueOnce({
response: {
status: 500,
error: { message: "Internal server error" }
}
});
const client = new TuitioClient("https://test.com/api");
try {
await client.authenticate("user", "pass");
} catch (error: any) {
expect(error.response.status).toBe(500);
expect(error.response.error.message).toBe("Internal server error");
}
});