saleor-dashboard/src/auth/AuthProvider.test.ts

97 lines
2.4 KiB
TypeScript
Raw Normal View History

2020-07-21 13:55:50 +00:00
import setupApi from "@test/api";
import { act, renderHook } from "@testing-library/react-hooks";
import ApolloClient from "apollo-client";
2021-01-26 22:04:54 +00:00
import { useAuthProvider } from "./hooks/useAuthProvider";
import { getTokens, setAuthToken } from "./utils";
2020-07-21 13:55:50 +00:00
const apolloClient = setupApi();
function renderAuthProvider(apolloClient: ApolloClient<any>) {
const intl = {
formatMessage: ({ defaultMessage }) => defaultMessage
};
const notify = jest.fn();
const { result } = renderHook(() =>
2021-01-26 22:04:54 +00:00
useAuthProvider({ apolloClient, intl: intl as any, notify })
2020-07-21 13:55:50 +00:00
);
return result;
}
const adminCredentials = {
2020-07-21 13:55:50 +00:00
email: "admin@example.com",
password: "admin",
token: null
2020-07-21 13:55:50 +00:00
};
const nonStaffUserCredentials = {
email: "client@example.com",
password: "password"
};
2020-07-21 13:55:50 +00:00
beforeEach(() => {
localStorage.clear();
2020-07-23 13:37:39 +00:00
sessionStorage.clear();
2020-07-21 13:55:50 +00:00
});
describe("User", () => {
it("will be logged in if has valid credentials", async done => {
const hook = renderAuthProvider(apolloClient);
await act(() =>
hook.current.login(adminCredentials.email, adminCredentials.password)
2020-07-21 13:55:50 +00:00
);
2021-01-26 22:04:54 +00:00
expect(hook.current.user.email).toBe(adminCredentials.email);
adminCredentials.token = getTokens().auth;
2020-07-21 13:55:50 +00:00
done();
});
it("will not be logged in if doesn't have valid credentials", async done => {
const hook = renderAuthProvider(apolloClient);
await act(() =>
hook.current.login(adminCredentials.email, "NotAValidPassword123!")
2020-07-21 13:55:50 +00:00
);
2021-01-26 22:04:54 +00:00
expect(hook.current.user).toBe(null);
2020-07-21 13:55:50 +00:00
done();
});
it("will not be logged in if is non-staff", async done => {
const hook = renderAuthProvider(apolloClient);
await act(() =>
hook.current.login(
nonStaffUserCredentials.email,
nonStaffUserCredentials.password
)
);
2021-01-26 22:04:54 +00:00
expect(hook.current.user).toBe(undefined);
done();
});
2020-07-21 13:55:50 +00:00
it("will be logged if has valid token", async done => {
setAuthToken(adminCredentials.token, false);
2020-07-21 13:55:50 +00:00
const hook = renderAuthProvider(apolloClient);
await act(() => hook.current.autologinPromise.current);
2021-01-26 22:04:54 +00:00
expect(hook.current.user.email).toBe(adminCredentials.email);
2020-07-21 13:55:50 +00:00
done();
});
it("will not be logged if has invalid token", async done => {
setAuthToken("NotAToken", false);
2020-07-21 13:55:50 +00:00
const hook = renderAuthProvider(apolloClient);
await act(() => hook.current.autologinPromise.current);
2021-01-26 22:04:54 +00:00
expect(hook.current.user).toBe(undefined);
2020-07-21 13:55:50 +00:00
done();
});
});