diff --git a/lattice/src/services/__mocks__/eventServices.tsx b/lattice/src/services/__mocks__/eventServices.tsx new file mode 100644 index 000000000..a6203b244 --- /dev/null +++ b/lattice/src/services/__mocks__/eventServices.tsx @@ -0,0 +1,12 @@ +const pilosa = { + get: { + auth() { + return new Promise((resolve, reject) => {}); + }, + userinfo() { + return new Promise((resolve, reject) => {}); + }, + }, +}; + +module.exports.pilosa = pilosa; diff --git a/lattice/src/services/useAuth.test.tsx b/lattice/src/services/useAuth.test.tsx new file mode 100644 index 000000000..964fba821 --- /dev/null +++ b/lattice/src/services/useAuth.test.tsx @@ -0,0 +1,95 @@ +import { AxiosResponse } from 'axios'; +import { act } from 'react-dom/test-utils'; +import ReactDOM from 'react-dom'; + +import { ProvideAuth, useAuth } from 'services/useAuth'; +import { pilosa } from './eventServices'; +jest.mock('./eventServices'); + +const AUTHENTICATED = 'Authenticated'; +const NOTAUTHED = 'Not Authed'; +const AUTHOFF = 'Auth off'; + +function TestUseAuthComponent() { + const auth = useAuth(); + + if (auth.isAuthOn === true && auth.isAuthenticated === true) { + return
{AUTHENTICATED}
; + } else if (auth.isAuthOn === true && auth.isAuthenticated === false) { + return
{NOTAUTHED}
; + } else { + return
{AUTHOFF}
; + } +} + +beforeEach(() => { + jest.clearAllMocks(); +}); + +test('useAuth - expect authenticated', async () => { + const mockResponse: AxiosResponse = { + status: 200, + data: 'OK', + statusText: '', + headers: {}, + config: {}, + }; + const root = document.createElement('root'); + await act(async () => { + jest.spyOn(pilosa.get, 'auth').mockResolvedValueOnce(mockResponse); + ReactDOM.render( + + + , + root + ); + }); + expect(pilosa.get.auth).toHaveBeenCalledTimes(1); + expect(root.innerHTML).toContain(AUTHENTICATED); +}); + +test('test useAuth - expect not authed', async () => { + const mockResponse: AxiosResponse = { + status: 200, + data: '', + statusText: '', + headers: {}, + config: {}, + }; + + const root = document.createElement('root'); + await act(async () => { + jest.spyOn(pilosa.get, 'auth').mockResolvedValueOnce(mockResponse); + ReactDOM.render( + + + , + root + ); + }); + expect(pilosa.get.auth).toHaveBeenCalledTimes(1); + expect(root.innerHTML).toContain(NOTAUTHED); +}); + +test('test useAuth - expect auth off', async () => { + const mockResponse: AxiosResponse = { + status: 204, + data: '', + statusText: '', + headers: {}, + config: {}, + }; + + const root = document.createElement('root'); + await act(async () => { + jest.spyOn(pilosa.get, 'auth').mockResolvedValueOnce(mockResponse); + ReactDOM.render( + + + , + root + ); + }); + expect(pilosa.get.auth).toHaveBeenCalledTimes(1); + expect(root.innerHTML).toContain(AUTHOFF); +});