Skip to content

Commit

Permalink
chore: improve check scope solution
Browse files Browse the repository at this point in the history
  • Loading branch information
afonsojramos committed Dec 6, 2023
1 parent 86b8269 commit 4757dc5
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 74 deletions.
95 changes: 45 additions & 50 deletions src/routes/Settings.test.tsx
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
import { fireEvent, render } from '@testing-library/react';
import React from 'react';
import TestRenderer, { act } from 'react-test-renderer';
import { render, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import TestRenderer, { act } from 'react-test-renderer';

const { ipcRenderer } = require('electron');

import { SettingsRoute } from './Settings';
import { AppContext } from '../context/App';
import { AxiosResponse } from 'axios';
import { mockAccounts, mockSettings } from '../__mocks__/mock-state';
import { AppContext } from '../context/App';
import * as apiRequests from '../utils/api-requests';
import Constants from '../utils/constants';
import { SettingsRoute } from './Settings';

const mockNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));
jest.spyOn(apiRequests, 'apiRequestAuth').mockResolvedValue({
headers: {
'x-oauth-scopes': Constants.AUTH_SCOPE.join(', '),
},
} as unknown as AxiosResponse);

describe('routes/Settings.tsx', () => {
const updateSetting = jest.fn();

beforeEach(() => {
mockNavigate.mockReset();
updateSetting.mockReset();
jest.clearAllMocks();
});

it('should render itself & its children', async () => {
Expand Down Expand Up @@ -77,7 +83,12 @@ describe('routes/Settings.tsx', () => {

await act(async () => {
const { getByLabelText: getByLabelTextLocal } = render(
<AppContext.Provider value={{ settings: mockSettings, accounts: mockAccounts }}>
<AppContext.Provider
value={{
settings: mockSettings,
accounts: mockAccounts,
}}
>
<MemoryRouter>
<SettingsRoute />
</MemoryRouter>
Expand Down Expand Up @@ -261,7 +272,12 @@ describe('routes/Settings.tsx', () => {

await act(async () => {
const { getByLabelText: getByLabelTextLocal } = render(
<AppContext.Provider value={{ settings: mockSettings, accounts: mockAccounts }}>
<AppContext.Provider
value={{
settings: mockSettings,
accounts: mockAccounts,
}}
>
<MemoryRouter>
<SettingsRoute />
</MemoryRouter>
Expand Down Expand Up @@ -298,27 +314,19 @@ describe('routes/Settings.tsx', () => {

it('should be able to enable colors', async () => {
let getByLabelText;
jest.mock('../utils/api-requests', () => ({
...jest.requireActual('../utils/api-requests'),
apiRequestAuth: jest.fn().mockResolvedValue({
headers: {
'x-oauth-scopes': Constants.AUTH_SCOPE.join(', '),
'access-control-allow-headers': 'Authorization',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'X-OAuth-Scopes',
'cache-control': 'private, max-age=60, s-maxage=60',
'content-encoding': 'gzip',
'content-security-policy': "default-src 'none'",
'content-type': 'application/json; charset=utf-8',
server: 'GitHub.com',
'strict-transport-security':
'max-age=31536000; includeSubdomains; preload',
vary: 'Accept, Authorization, Cookie, X-GitHub-OTP, Accept-Encoding, Accept, X-Requested-With',
},
}),
}));
let findByLabelText;

jest.spyOn(apiRequests, 'apiRequestAuth').mockResolvedValue({
headers: {
'x-oauth-scopes': Constants.AUTH_SCOPE.join(', '),
},
} as unknown as AxiosResponse);

await act(async () => {
const { getByLabelText: getByLabelTextLocal } = render(
const {
getByLabelText: getByLabelTextLocal,
findByLabelText: findByLabelTextLocal,
} = render(
<AppContext.Provider
value={{
settings: mockSettings,
Expand All @@ -332,34 +340,25 @@ describe('routes/Settings.tsx', () => {
</AppContext.Provider>,
);
getByLabelText = getByLabelTextLocal;
findByLabelText = findByLabelTextLocal;
});

// await act(async () => {
// expect(getByLabelText('Use GitHub-like state colors')).toBeDefined();
// });
await findByLabelText('Use GitHub-like state colors');

// await act(async () => {
await act(
() =>
// waitFor(() =>
fireEvent.click(getByLabelText('Use GitHub-like state colors')),
// ),
);
fireEvent.click(getByLabelText('Use GitHub-like state colors'));

expect(updateSetting).toHaveBeenCalledTimes(1);
expect(updateSetting).toHaveBeenCalledWith('colors', true);
});

it('should not be able to disable colors', async () => {
let queryByLabelText;
jest.mock('../utils/helpers', () => ({
...jest.requireActual('../utils/helpers'),
apiRequestAuth: jest.fn().mockResolvedValue({
headers: {
'x-oauth-scopes': 'repo, notifications',
},
}),
}));

jest.spyOn(apiRequests, 'apiRequestAuth').mockResolvedValue({
headers: {
'x-oauth-scopes': 'read:user, notifications',
},
} as unknown as AxiosResponse);

await act(async () => {
const { queryByLabelText: queryByLabelLocal } = render(
Expand All @@ -377,10 +376,6 @@ describe('routes/Settings.tsx', () => {
queryByLabelText = queryByLabelLocal;
});

console.log(
queryByLabelText('Use GitHub-like state colors (requires re-auth)'),
);

expect(
queryByLabelText('Use GitHub-like state colors (requires re-auth)'),
).toBeDefined();
Expand Down
42 changes: 21 additions & 21 deletions src/routes/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import React, { useCallback, useContext, useState, useEffect } from 'react';
import { ArrowLeftIcon } from '@primer/octicons-react';
import { ipcRenderer } from 'electron';
import React, {
useCallback,
useContext,
useEffect,
useMemo,
useState,
} from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeftIcon } from '@primer/octicons-react';

import { AppContext } from '../context/App';
import { Appearance } from '../types';
import { FieldCheckbox } from '../components/fields/Checkbox';
import { FieldRadioGroup } from '../components/fields/RadioGroup';
import { AppContext } from '../context/App';
import { IconAddAccount } from '../icons/AddAccount';
import { IconLogOut } from '../icons/Logout';
import { IconQuit } from '../icons/Quit';
import { updateTrayIcon } from '../utils/comms';
import { setAppearance } from '../utils/appearance';
import { Appearance } from '../types';
import { apiRequestAuth } from '../utils/api-requests';
import { generateGitHubAPIUrl } from '../utils/helpers';
import { setAppearance } from '../utils/appearance';
import { updateTrayIcon } from '../utils/comms';
import Constants from '../utils/constants';
import { generateGitHubAPIUrl } from '../utils/helpers';

export const SettingsRoute: React.FC = () => {
const { accounts, settings, updateSetting, logout } = useContext(AppContext);
Expand All @@ -32,28 +38,22 @@ export const SettingsRoute: React.FC = () => {
ipcRenderer.invoke('get-app-version').then((result: string) => {
setAppVersion(result);
});
}, []);

useMemo(() => {
(async () => {
const response = await apiRequestAuth(
`${generateGitHubAPIUrl(Constants.DEFAULT_AUTH_OPTIONS.hostname)}`,
'GET',
accounts.token,
);

console.log(JSON.stringify(response.headers));
const missingScopes = Constants.AUTH_SCOPE.filter((scope) => {
return !response.headers['x-oauth-scopes'].includes(scope);
});
if (missingScopes.length > 0) {
new Notification('Gitify - Permissions', {
body:
'You need to grant all the permissions to use this app. Missing scopes: ' +
missingScopes.join(', ') +
'.',
});
} else setColorScope(true);
console.info("Token's scopes:", response.headers['x-oauth-scopes']);

if (response.headers['x-oauth-scopes'].includes('repo'))
setColorScope(true);
})();
}, []);
}, [accounts.token]);

ipcRenderer.on('update-native-theme', (_, updatedAppearance: Appearance) => {
if (settings.appearance === Appearance.SYSTEM) {
Expand Down Expand Up @@ -110,7 +110,7 @@ export const SettingsRoute: React.FC = () => {
<FieldCheckbox
name="colors"
label={`Use GitHub-like state colors${
!colorScope ? ' (requires re-auth)' : ''
!colorScope ? ' (requires repo scope)' : ''
}`}
checked={colorScope && settings.colors}
onChange={(evt) => updateSetting('colors', evt.target.checked)}
Expand Down
6 changes: 3 additions & 3 deletions src/routes/__snapshots__/Settings.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ exports[`routes/Settings.tsx should render itself & its children 1`] = `
<input
checked={false}
className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
disabled={true}
disabled={false}
id="colors"
onChange={[Function]}
type="checkbox"
Expand All @@ -142,11 +142,11 @@ exports[`routes/Settings.tsx should render itself & its children 1`] = `
htmlFor="colors"
style={
{
"textDecoration": "line-through",
"textDecoration": false,
}
}
>
Use GitHub-like state colors (requires re-auth)
Use GitHub-like state colors
</label>
</div>
</div>
Expand Down

0 comments on commit 4757dc5

Please sign in to comment.