homebox/frontend/lib/api/__test__/test-utils.ts

45 lines
1.2 KiB
TypeScript
Raw Permalink Normal View History

import { beforeAll, expect } from "vitest";
import { UserClient } from "../user";
import { factories } from "./factories";
2022-09-05 00:37:37 +00:00
const cache = {
token: "",
2022-09-05 00:37:37 +00:00
};
/*
* Shared UserApi token for tests where the creation of a user is _not_ import
* to the test. This is useful for tests that are testing the user API itself.
*/
export async function sharedUserClient(): Promise<UserClient> {
2022-09-05 00:37:37 +00:00
if (cache.token) {
return factories.client.user(cache.token);
2022-09-05 00:37:37 +00:00
}
const testUser = {
email: "__test__@__test__.com",
name: "__test__",
password: "__test__",
token: "",
2022-09-05 00:37:37 +00:00
};
const api = factories.client.public();
const { response: tryLoginResp, data } = await api.login(testUser.email, testUser.password);
2022-09-05 00:37:37 +00:00
if (tryLoginResp.status === 200) {
cache.token = data.token;
return factories.client.user(cache.token);
2022-09-05 00:37:37 +00:00
}
const { response: registerResp } = await api.register(testUser);
expect(registerResp.status).toBe(204);
const { response: loginResp, data: loginData } = await api.login(testUser.email, testUser.password);
2022-09-05 00:37:37 +00:00
expect(loginResp.status).toBe(200);
cache.token = loginData.token;
return factories.client.user(data.token);
2022-09-05 00:37:37 +00:00
}
2022-09-05 00:46:05 +00:00
beforeAll(async () => {
await sharedUserClient();
});