Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrate scigateway tests to testing-library #1273

Merged
merged 31 commits into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
37661f5
Migrate accessibility page tests to RTL
kennethnym Feb 20, 2023
7da2f88
Migrate contact us tests to RTL
kennethnym Feb 20, 2023
5662d3f
Migrate admin page tests to RTL
kennethnym Feb 20, 2023
1d85292
Migrate maintenance page tests to RTL
kennethnym Feb 20, 2023
a709aa7
Migrate cookie consent tests to RTL
kennethnym Feb 20, 2023
4165a06
Migrate cookies page tests to RTL
kennethnym Feb 20, 2023
62cff8f
Migrate footer tests to RTL
kennethnym Feb 20, 2023
5adf3e3
Migrate help page tests to RTL
kennethnym Feb 20, 2023
9a981a1
Migrate home page tests to RTL
kennethnym Feb 20, 2023
c69d673
Migrate useAnchor tests to RTL
kennethnym Feb 20, 2023
155d1bb
Migrate login page tests to RTL
kennethnym Mar 10, 2023
2cdafae
Migrate logout page tests to RTL
kennethnym Mar 10, 2023
f30b16f
Migrate main app bar tests to RTL
kennethnym Mar 10, 2023
247816f
Migrate maintenance page tests to RTL
kennethnym Mar 10, 2023
328ac55
Migrate user profile tests to RTL
kennethnym Mar 10, 2023
6fa056b
Migrate page not found tests to RTL
kennethnym Mar 10, 2023
3bd25fe
Migrate preloader tests to RTL
kennethnym Mar 10, 2023
8029ca3
Migrate preloader tests to RTL
kennethnym Mar 10, 2023
3837f39
Migrate routing tests to RTL
kennethnym Mar 10, 2023
0ed70b4
Migrate page container tests to RTL
kennethnym Mar 10, 2023
b21150f
Migrate notification badge tests to RTL
kennethnym Mar 10, 2023
9583580
Missed a test in login page
kennethnym Mar 13, 2023
701228c
Migrate navigation drawer tests to RTL
kennethnym Mar 14, 2023
2e7170a
Migrate rest of tests to RTL
kennethnym Mar 17, 2023
551c7ff
Remove enzyme dependencies 🎉
kennethnym Mar 17, 2023
f1f445a
Remove unused var assignment
kennethnym Mar 17, 2023
020128e
Update obsolete test snapshots
kennethnym Mar 17, 2023
868371f
Fix warnings/errors in unit tests log output
louise-davies Mar 22, 2023
e2ce0b8
Add test for App maintenance state check
louise-davies Mar 22, 2023
74f4034
Move useRealTimers call to afterEach
kennethnym Mar 22, 2023
0a86e5c
Merge remote-tracking branch 'origin/enhancement/rtl-migration' into …
kennethnym Mar 22, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,6 @@
"extends": "react-app"
},
"jest": {
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"collectCoverageFrom": [
"src/**/*.{tsx,js,jsx,ts}",
"!src/index.tsx",
Expand Down Expand Up @@ -116,14 +113,11 @@
"@types/redux-mock-store": "1.0.2",
"@typescript-eslint/eslint-plugin": "5.49.0",
"@typescript-eslint/parser": "5.49.0",
"@wojtekmaj/enzyme-adapter-react-17": "0.6.6",
"axios-mock-adapter": "1.21.1",
"babel-eslint": "10.1.0",
"concurrently": "7.6.0",
"cross-env": "7.0.3",
"cypress": "12.3.0",
"enzyme": "3.11.0",
"enzyme-to-json": "3.6.2",
"eslint": "8.33.0",
"eslint-config-react-app": "7.0.0",
"lint-staged": "13.1.0",
Expand Down
94 changes: 48 additions & 46 deletions src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
import { mount, shallow } from 'enzyme';
import axios from 'axios';
import React from 'react';
import ReactDOM from 'react-dom';
import { act } from 'react-dom/test-utils';
import { Provider } from 'react-redux';
import * as singleSpa from 'single-spa';
import App, { AppSansHoc } from './App';
import { act, fireEvent, render, screen } from '@testing-library/react';
import { flushPromises } from './setupTests';
import { loadAuthProvider } from './state/actions/scigateway.actions';
import { Preloader } from './preloader/preloader.component';
import axios from 'axios';
import { RegisterRouteType } from './state/scigateway.types';

describe('App', () => {
beforeEach(() => {
singleSpa.start();
});
jest.mock('./state/actions/loadMicroFrontends', () => ({
init: jest.fn(() => Promise.resolve()),
singleSpaPluginRoutes: ['/plugin1'],
}));

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) => {
return name === 'scigateway:token' ? testToken : null;
});

describe('App', () => {
afterEach(() => {
jest.useRealTimers();
});
Expand All @@ -26,46 +31,45 @@ describe('App', () => {
});

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

it('loadMaintenanceState dispatched when maintenance changes', async () => {
// this test only works with old jest fake timers
// when they remove legacy timers refactor this test to use real timers
jest.useFakeTimers('legacy');
(axios.get as jest.Mock).mockImplementation(() =>
// mock so token verify succeeds
(axios.post as jest.Mock).mockImplementation(() =>
Promise.resolve({
data: {
show: true,
message: '',
},
data: {},
})
);
window.matchMedia = jest.fn().mockReturnValue({ matches: true });

const wrapper = mount(<App useSuspense={false} />);
const realStore = wrapper.find(Provider).prop('store');
// Set provider to icat as that supports maintenance states
realStore.dispatch(
loadAuthProvider('icat.user/pass', 'http://localhost:8000')
jest.useFakeTimers();

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

const registerRouteAction = {
type: RegisterRouteType,
payload: {
section: 'test',
link: '/plugin1',
plugin: 'test_plugin',
displayName: 'Test plugin',
order: 0,
},
};
document.dispatchEvent(
new CustomEvent('scigateway', {
detail: registerRouteAction,
})
);
expect(realStore.getState().scigateway.maintenance).toEqual({
show: false,
message: '',
});

jest.runOnlyPendingTimers();
await act(async () => {
await flushPromises();
wrapper.update();
});
// go to plugin page
await fireEvent.click(screen.getByRole('link', { name: 'Test plugin' }));

expect(realStore.getState().scigateway.maintenance).toEqual({
show: true,
message: '',
});
expect(document.getElementById('test_plugin')).toBeInTheDocument();

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

(axios.get as jest.Mock).mockImplementation(() =>
Promise.resolve({
Expand All @@ -77,14 +81,12 @@ describe('App', () => {
);

jest.runOnlyPendingTimers();

await act(async () => {
await flushPromises();
wrapper.update();
});

expect(realStore.getState().scigateway.maintenance).toEqual({
show: true,
message: 'test message',
});
expect(screen.getByText('Maintenance')).toBeInTheDocument();
expect(screen.getByText('test message')).toBeInTheDocument();
});
});
2 changes: 0 additions & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ const middleware = [
if (process.env.NODE_ENV === `development`) {
const logger = createLogger({ collapsed: true });
middleware.push(logger);
// const {whyDidYouUpdate} = require('why-did-you-update');
// whyDidYouUpdate(React);
log.setDefaultLevel(log.levels.DEBUG);
} else {
log.setDefaultLevel(log.levels.ERROR);
Expand Down
5 changes: 4 additions & 1 deletion src/__mocks__/axios.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ const requests = {
if (path === '/settings.json') {
return Promise.resolve({
data: {
'auth-provider': 'jwt',
// Set provider to icat as that supports maintenance states needed for App.test.tsx
'auth-provider': expect.getState().testPath?.includes('App.test')
? 'icat'
: 'jwt',
'ui-strings': '/res/default.json',
plugins: [],
'help-tour-steps': [],
Expand Down
5 changes: 3 additions & 2 deletions src/__mocks__/react-i18next.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ const renderNodes = (reactNodes) => {
});
};

const useMock = [(k) => k, {}];
useMock.t = (k) => k;
const t = (k, opt) => (opt && 'returnObjects' in opt ? [`${k}0`, `${k}1`] : k);
const useMock = [t, {}];
useMock.t = t;
useMock.i18n = {};

const applyTranslation = (Component) => {
Expand Down
8 changes: 5 additions & 3 deletions src/__snapshots__/example.component.test.tsx.snap
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Example component renders correctly 1`] = `
<div>
test notification
</div>
<DocumentFragment>
<div>
test notification
</div>
</DocumentFragment>
`;
Loading