Skip to content

Commit

Permalink
Fix global mocking behavour and vscode linting in tests and replace s…
Browse files Browse the repository at this point in the history
…ome jest with vi #1379
  • Loading branch information
joelvdavies committed Mar 13, 2024
1 parent c0f3258 commit 9561d42
Show file tree
Hide file tree
Showing 27 changed files with 177 additions and 166 deletions.
4 changes: 2 additions & 2 deletions src/__mocks__/axios.ts → __mocks__/axios.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// TODO: move __mocks__ folder back to root once facebook/create-react-app#7539 is fixed

const requests = {
get: jest.fn((path) => {
get: vi.fn((path) => {
if (path === '/settings.json') {
return Promise.resolve({
data: {
Expand All @@ -20,7 +20,7 @@ const requests = {
});
}
}),
post: jest.fn(() => Promise.resolve({ data: {} })),
post: vi.fn(() => Promise.resolve({ data: {} })),
};

export default requests;
File renamed without changes.
43 changes: 21 additions & 22 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,37 +1,36 @@
import React from 'react';
import { useMediaQuery } from '@mui/material';
import { act, fireEvent, render, screen } from '@testing-library/react';
import axios from 'axios';
import { createRoot } from 'react-dom/client';
import App, { AppSansHoc } from './App';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { flushPromises } from './setupTests';
import axios from 'axios';
import { RegisterRouteType } from './state/scigateway.types';
import { useMediaQuery } from '@mui/material';

jest.mock('./state/actions/loadMicroFrontends', () => ({
init: jest.fn(() => Promise.resolve()),
vi.mock('./state/actions/loadMicroFrontends', () => ({
init: vi.fn(() => Promise.resolve()),
singleSpaPluginRoutes: ['/plugin1'],
}));
jest.mock('@mui/material', () => ({
vi.mock('@mui/material', async () => ({
__esmodule: true,
...jest.requireActual('@mui/material'),
useMediaQuery: jest.fn(),
...(await vi.importActual('@mui/material')),
useMediaQuery: vi.fn(),
}));

const testToken =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.hNQI_r8BATy1LyXPr6Zuo9X_V0kSED8ngcqQ6G-WV5w';

// needed for the maintenance state update test - for some reason it doesn't work when at the beginning of the test itself
window.localStorage.__proto__.getItem = jest.fn().mockImplementation((name) => {
window.localStorage.__proto__.getItem = vi.fn().mockImplementation((name) => {
return name === 'scigateway:token' ? testToken : null;
});

describe('App', () => {
beforeEach(() => {
jest.mocked(useMediaQuery).mockReturnValue(true);
vi.mocked(useMediaQuery).mockReturnValue(true);
});

afterEach(() => {
jest.useRealTimers();
vi.useRealTimers();
});

it('renders without crashing', () => {
Expand All @@ -46,27 +45,27 @@ describe('App', () => {
});

it('should show preloader when react-i18next is not ready', () => {
render(<AppSansHoc t={jest.fn()} i18n={{}} tReady={false} />);
render(<AppSansHoc t={vi.fn()} i18n={{}} tReady={false} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});

it('should dispatch loadMaintenanceState and force refresh the page when maintenance changes', async () => {
// mock so token verify succeeds
(axios.post as jest.Mock).mockImplementation(() =>
(axios.post as vi.Mock).mockImplementation(() =>
Promise.resolve({
data: {},
})
);
window.matchMedia = jest.fn().mockReturnValue({ matches: true });
window.matchMedia = vi.fn().mockReturnValue({ matches: true });

Object.defineProperty(window, 'location', {
configurable: true,
value: { reload: jest.fn() },
value: { reload: vi.fn() },
});

jest.useFakeTimers();
vi.useFakeTimers();

render(<AppSansHoc t={jest.fn()} i18n={{}} tReady={true} />);
render(<AppSansHoc t={vi.fn()} i18n={{}} tReady={true} />);

const registerRouteAction = {
type: RegisterRouteType,
Expand Down Expand Up @@ -94,7 +93,7 @@ describe('App', () => {

expect(screen.queryByText('Maintenance')).not.toBeInTheDocument();

(axios.get as jest.Mock).mockImplementation(() =>
(axios.get as vi.Mock).mockImplementation(() =>
Promise.resolve({
data: {
show: true,
Expand All @@ -104,7 +103,7 @@ describe('App', () => {
);

act(() => {
jest.runOnlyPendingTimers();
vi.runOnlyPendingTimers();
});

await act(async () => {
Expand All @@ -117,7 +116,7 @@ describe('App', () => {
// should not refresh page when maintenance state changes from false to true
expect(window.location.reload).not.toHaveBeenCalled();

(axios.get as jest.Mock).mockImplementation(() =>
(axios.get as vi.Mock).mockImplementation(() =>
Promise.resolve({
data: {
show: false,
Expand All @@ -126,7 +125,7 @@ describe('App', () => {
})
);

jest.runOnlyPendingTimers();
vi.runOnlyPendingTimers();

await act(async () => {
await flushPromises();
Expand Down
16 changes: 8 additions & 8 deletions src/authentication/githubAuthProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ describe('github auth provider', () => {
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.hNQI_r8BATy1LyXPr6Zuo9X_V0kSED8ngcqQ6G-WV5w';

beforeEach(() => {
jest.spyOn(window.localStorage.__proto__, 'getItem');
window.localStorage.__proto__.getItem = jest
vi.spyOn(window.localStorage.__proto__, 'getItem');
window.localStorage.__proto__.getItem = vi
.fn()
.mockImplementation((name) =>
name === 'scigateway:token' ? testToken : null
);
window.localStorage.__proto__.removeItem = jest.fn();
window.localStorage.__proto__.setItem = jest.fn();
window.localStorage.__proto__.removeItem = vi.fn();
window.localStorage.__proto__.setItem = vi.fn();

authProvider = new GithubAuthProvider('http://localhost:8000');
});
Expand All @@ -32,7 +32,7 @@ describe('github auth provider', () => {
});

it('should call the api to verify code', async () => {
(mockAxios.post as jest.Mock).mockImplementation(() =>
(mockAxios.post as vi.Mock).mockImplementation(() =>
Promise.resolve({
data: {
token: testToken,
Expand Down Expand Up @@ -63,7 +63,7 @@ describe('github auth provider', () => {
});

it('should log the user out if code is invalid', async () => {
(mockAxios.post as jest.Mock).mockImplementation(() =>
(mockAxios.post as vi.Mock).mockImplementation(() =>
Promise.reject({
response: {
status: 401,
Expand All @@ -80,7 +80,7 @@ describe('github auth provider', () => {
});

it('should log the user out if the token has expired', async () => {
(mockAxios.post as jest.Mock).mockImplementation(() =>
(mockAxios.post as vi.Mock).mockImplementation(() =>
Promise.reject({
response: {
status: 401,
Expand All @@ -97,7 +97,7 @@ describe('github auth provider', () => {
});

it('should return user information if token is valid', async () => {
(mockAxios.post as jest.Mock).mockImplementation(() =>
(mockAxios.post as vi.Mock).mockImplementation(() =>
Promise.resolve({
data: {
username: 'test_user',
Expand Down
18 changes: 9 additions & 9 deletions src/authentication/icatAuthProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import ICATAuthProvider from './icatAuthProvider';
import parseJwt from './parseJwt';
import { BroadcastSignOutType } from '../state/scigateway.types';

jest.mock('./parseJwt');
vi.mock('./parseJwt');

describe('ICAT auth provider', () => {
let icatAuthProvider: ICATAuthProvider;
Expand All @@ -22,8 +22,8 @@ describe('ICAT auth provider', () => {
return null;
}
});
window.localStorage.__proto__.removeItem = jest.fn();
window.localStorage.__proto__.setItem = jest.fn();
window.localStorage.__proto__.removeItem = vi.fn();
window.localStorage.__proto__.setItem = vi.fn();

icatAuthProvider = new ICATAuthProvider(
'mnemonic',
Expand All @@ -35,7 +35,7 @@ describe('ICAT auth provider', () => {
`{"sessionId": "${token}", "username": "${token} username", "userIsAdmin": true}`
);

document.dispatchEvent = jest.fn();
document.dispatchEvent = vi.fn();
});

it('should set the mnemonic to empty string if none is provided (after autologin)', async () => {
Expand Down Expand Up @@ -160,7 +160,7 @@ describe('ICAT auth provider', () => {
);

// ensure token is null
window.localStorage.__proto__.getItem = jest.fn().mockReturnValue(null);
window.localStorage.__proto__.getItem = vi.fn().mockReturnValue(null);

icatAuthProvider = new ICATAuthProvider(
undefined,
Expand Down Expand Up @@ -196,7 +196,7 @@ describe('ICAT auth provider', () => {
);

// ensure token is null
window.localStorage.__proto__.getItem = jest.fn().mockReturnValue(null);
window.localStorage.__proto__.getItem = vi.fn().mockReturnValue(null);

icatAuthProvider = new ICATAuthProvider(
undefined,
Expand Down Expand Up @@ -372,7 +372,7 @@ describe('ICAT auth provider', () => {

it('should call api to set scheduled maintenance state', async () => {
const scheduledMaintenanceState = { show: true, message: 'test' };
mockAxios.put = jest.fn().mockImplementation(() =>
mockAxios.put = vi.fn().mockImplementation(() =>
Promise.resolve({
data: 'test',
})
Expand All @@ -393,7 +393,7 @@ describe('ICAT auth provider', () => {

it('should log the user out if it fails to set scheduled maintenance state', async () => {
const scheduledMaintenanceState = { show: true, message: 'test' };
mockAxios.put = jest.fn().mockImplementation(() =>
mockAxios.put = vi.fn().mockImplementation(() =>
Promise.reject({
response: {
status: 401,
Expand Down Expand Up @@ -427,7 +427,7 @@ describe('ICAT auth provider', () => {

it('should log the user out if it fails to set maintenance state', async () => {
const maintenanceState = { show: true, message: 'test' };
mockAxios.put = jest.fn().mockImplementation(() =>
mockAxios.put = vi.fn().mockImplementation(() =>
Promise.reject({
response: {
status: 401,
Expand Down
6 changes: 3 additions & 3 deletions src/authentication/jwtAuthProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@ describe('jwt auth provider', () => {
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InVzZXIiLCJ1c2VySXNBZG1pbiI6ZmFsc2V9.PEuKaAD98doFTLyqcNFpsuv50AQR8ejrbDQ0pwazM7Q';

beforeEach(() => {
jest.spyOn(window.localStorage.__proto__, 'getItem');
vi.spyOn(window.localStorage.__proto__, 'getItem');
window.localStorage.__proto__.getItem = jest
.fn()
.mockImplementation((name) =>
name === 'scigateway:token' ? testToken : null
);
window.localStorage.__proto__.removeItem = jest.fn();
window.localStorage.__proto__.setItem = jest.fn();
window.localStorage.__proto__.removeItem = vi.fn();
window.localStorage.__proto__.setItem = vi.fn();

jwtAuthProvider = new JWTAuthProvider('http://localhost:8000');
});
Expand Down
4 changes: 2 additions & 2 deletions src/cookieConsent/cookieConsent.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ describe('Cookie consent component', () => {
});

it('should set cookie to true upon user accept', async () => {
Cookies.set = jest.fn();
Cookies.set = vi.fn();
const user = userEvent.setup();

render(<CookieConsent />, { wrapper: Wrapper });
Expand All @@ -91,7 +91,7 @@ describe('Cookie consent component', () => {
});

it("initalises analytics if cookie consent is true but analytics hasn't yet been initialised", () => {
jest.spyOn(document.head, 'appendChild');
vi.spyOn(document.head, 'appendChild');

Cookies.get = jest
.fn()
Expand Down
6 changes: 3 additions & 3 deletions src/cookieConsent/cookiesPage.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { TOptionsBase } from 'i18next';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

jest.mock('react-i18next', () => ({
vi.mock('react-i18next', () => ({
useTranslation: () => {
return {
t: (key: string, options: TOptionsBase) =>
Expand All @@ -34,8 +34,8 @@ describe('Cookies page component', () => {
};
store = mockStore(state);

Cookies.set = jest.fn();
Cookies.remove = jest.fn();
Cookies.set = vi.fn();
Cookies.remove = vi.fn();
});

const theme = buildTheme(false);
Expand Down
4 changes: 2 additions & 2 deletions src/helpPage/helpPage.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import { render } from '@testing-library/react';
import { ThemeProvider } from '@mui/material';
import { buildTheme } from '../theming';

jest.mock('../hooks/useAnchor', () => ({
vi.mock('../hooks/useAnchor', () => ({
__esModule: true,
default: jest.fn(),
default: vi.fn(),
}));

describe('Help page component', () => {
Expand Down
4 changes: 2 additions & 2 deletions src/homePage/homePage.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { ThemeProvider } from '@mui/material';
import { buildTheme } from '../theming';
import { MemoryRouter } from 'react-router-dom';

jest.mock('@mui/material', () => ({
vi.mock('@mui/material', () => ({
__esmodule: true,
...jest.requireActual('@mui/material'),
useMediaQuery: jest.fn(() => true),
useMediaQuery: vi.fn(() => true),
}));

describe('Home page component', () => {
Expand Down
Loading

0 comments on commit 9561d42

Please sign in to comment.