Skip to content

Commit

Permalink
test: refactor test and mock reporting and workers for all tests
Browse files Browse the repository at this point in the history
* refactor: use direct import for reporting and remove index file

refs: SHELL-101 (#281)
  • Loading branch information
beawar authored Jul 10, 2023
1 parent d0c8399 commit adaecfd
Show file tree
Hide file tree
Showing 17 changed files with 129 additions and 147 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
},
"scripts": {
"build:clean": "rm -rf lib && rm -rf dist && rm -rf pkg",
"test": "jest",
"test:ci": "jest --testTimeout=10000 --maxWorkers=50%",
"test:dev": "jest",
"test": "is-ci && npm run test:ci || npm run test:dev",
"prepare": "is-ci || husky install",
"prepack": "npm run build:clean && npm run build -- -d",
"postpublish": "rm -rf lib",
Expand Down
2 changes: 1 addition & 1 deletion src/boot/app/load-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { AppLink } from '../../ui-extras/app-link';
import * as CONSTANTS from '../../constants';
import type { CarbonioModule } from '../../../types';
import { getAppSetters } from './app-loader-setters';
import { report } from '../../reporting';
import { report } from '../../reporting/functions';
import SettingsHeader from '../../settings/components/settings-header';

export const _scripts: { [pkgName: string]: HTMLScriptElement } = {};
Expand Down
2 changes: 1 addition & 1 deletion src/boot/app/load-apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { registerLocale, setDefaultLocale } from '@zextras/carbonio-design-syste
import type { Locale as DateFnsLocale } from 'date-fns';
import { CarbonioModule } from '../../../types';
import { SHELL_APP_ID } from '../../constants';
import { useReporter } from '../../reporting';
import { useReporter } from '../../reporting/store';
import { getUserSetting, useAccountStore } from '../../store/account';
import { getT, useI18nStore } from '../../store/i18n';
import { loadApp, unloadApps } from './load-app';
Expand Down
99 changes: 51 additions & 48 deletions src/boot/loader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,15 @@
*/
import React from 'react';

import { act, screen, waitFor } from '@testing-library/react';
import { ResponseResolver, rest, RestContext, RestRequest } from 'msw';
import { act, screen } from '@testing-library/react';
import { rest } from 'msw';

import { Loader } from './loader';
import { LoginConfigStore } from '../../types/loginConfig';
import { LOGIN_V3_CONFIG_PATH } from '../constants';
import { getComponentsJson, GetComponentsJsonResponseBody } from '../mocks/handlers/components';
import { getInfoRequest } from '../mocks/handlers/getInfoRequest';
import { getLoginConfig } from '../mocks/handlers/login-config';
import server from '../mocks/server';
import { GetComponentsJsonResponseBody } from '../mocks/handlers/components';
import server, { waitForResponse } from '../mocks/server';
import { controlConsoleError, setup } from '../test/utils';

jest.mock<typeof import('../workers')>('../workers');
jest.mock<typeof import('../reporting/functions')>('../reporting/functions');

describe('Loader', () => {
test('If only getComponents request fails, the LoaderFailureModal appears', async () => {
// using getInfo and loginConfig default handlers
Expand All @@ -31,8 +25,19 @@ describe('Loader', () => {
)
);

setup(<Loader />);
const loginRes = waitForResponse('get', LOGIN_V3_CONFIG_PATH);
const componentsRes = waitForResponse('get', '/static/iris/components.json');
const getInfoRes = waitForResponse('post', '/service/soap/GetInfoRequest');

setup(
<span data-testid={'loader'}>
<Loader />
</span>
);
await loginRes;
await screen.findByTestId('loader');
await componentsRes;
await getInfoRes;
const title = await screen.findByText('Something went wrong...');
act(() => {
jest.runOnlyPendingTimers();
Expand All @@ -49,8 +54,18 @@ describe('Loader', () => {
res(ctx.status(503, 'Controlled error: fail getInfo request'))
)
);

setup(<Loader />);
const loginRes = waitForResponse('get', LOGIN_V3_CONFIG_PATH);
const componentsRes = waitForResponse('get', '/static/iris/components.json');
const getInfoRes = waitForResponse('post', '/service/soap/GetInfoRequest');
setup(
<span data-testid={'loader'}>
<Loader />
</span>
);
await loginRes;
await screen.findByTestId('loader');
await componentsRes;
await getInfoRes;

const title = await screen.findByText('Something went wrong...');
act(() => {
Expand All @@ -60,47 +75,35 @@ describe('Loader', () => {
});

test('If only loginConfig request fails, the LoaderFailureModal does not appear', async () => {
const getComponentsJsonHandler = jest.fn(getComponentsJson);
const getInfoHandler = jest.fn(getInfoRequest);
type LoginConfigHandler = ResponseResolver<
RestRequest<never, never>,
RestContext,
Partial<Omit<LoginConfigStore, 'loaded'>>
>;
const loginConfigHandler = jest.fn<
ReturnType<LoginConfigHandler>,
Parameters<LoginConfigHandler>
>((req, res, ctx) => res(ctx.status(503)));
server.use(
rest.get('/static/iris/components.json', getComponentsJsonHandler),
rest.post('/service/soap/GetInfoRequest', getInfoHandler),
rest.get(LOGIN_V3_CONFIG_PATH, loginConfigHandler)
server.use(rest.get(LOGIN_V3_CONFIG_PATH, (req, res, ctx) => res(ctx.status(503))));
const loginRes = waitForResponse('get', LOGIN_V3_CONFIG_PATH);
const componentsRes = waitForResponse('get', '/static/iris/components.json');
const getInfoRes = waitForResponse('post', '/service/soap/GetInfoRequest');
setup(
<span data-testid={'loader'}>
<Loader />
</span>
);

setup(<Loader />);

await waitFor(() => expect(loginConfigHandler).toHaveBeenCalled());
await waitFor(() => expect(getComponentsJsonHandler).toHaveBeenCalled());
await waitFor(() => expect(getInfoHandler).toHaveBeenCalled());

await loginRes;
await screen.findByTestId('loader');
await componentsRes;
await getInfoRes;
expect(screen.queryByText('Something went wrong...')).not.toBeInTheDocument();
});

test('If Loader requests do not fail, the LoaderFailureModal does not appear', async () => {
const loginConfigHandler = jest.fn(getLoginConfig);
const getComponentsJsonHandler = jest.fn(getComponentsJson);
const getInfoHandler = jest.fn(getInfoRequest);

server.use(
rest.get('/static/iris/components.json', getComponentsJsonHandler),
rest.post('/service/soap/GetInfoRequest', getInfoHandler),
rest.get(LOGIN_V3_CONFIG_PATH, loginConfigHandler)
const loginRes = waitForResponse('get', LOGIN_V3_CONFIG_PATH);
const componentsRes = waitForResponse('get', '/static/iris/components.json');
const getInfoRes = waitForResponse('post', '/service/soap/GetInfoRequest');
setup(
<span data-testid={'loader'}>
<Loader />
</span>
);
setup(<Loader />);

await waitFor(() => expect(loginConfigHandler).toHaveBeenCalled());
await waitFor(() => expect(getComponentsJsonHandler).toHaveBeenCalled());
await waitFor(() => expect(getInfoHandler).toHaveBeenCalled());
await loginRes;
await screen.findByTestId('loader');
await componentsRes;
await getInfoRes;

expect(screen.queryByText('Something went wrong...')).not.toBeInTheDocument();
});
Expand Down
20 changes: 8 additions & 12 deletions src/jest-env-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,6 @@ beforeEach(() => {
})
});

Object.defineProperty(window, 'ResizeObserver', {
writable: true,
value: function ResizeObserverMock(): ResizeObserver {
return {
observe: jest.fn(),
unobserve: jest.fn(),
disconnect: jest.fn()
};
}
});

// cleanup local storage
window.localStorage.clear();

Expand All @@ -78,9 +67,16 @@ afterAll(() => {
});

afterEach(() => {
jest.runOnlyPendingTimers();
act(() => {
jest.runOnlyPendingTimers();
});
server.events.removeAllListeners();
server.resetHandlers();
act(() => {
window.resizeTo(1024, 768);
});
});

jest.mock<typeof import('./workers')>('./workers');
jest.mock<typeof import('./reporting/functions')>('./reporting/functions');
jest.mock<typeof import('./reporting/store')>('./reporting/store');
11 changes: 11 additions & 0 deletions src/jest-polyfills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,14 @@ window.resizeTo = function resizeTo(width, height): void {
outerHeight: height
}).dispatchEvent(new this.Event('resize'));
};

Object.defineProperty(window, 'ResizeObserver', {
writable: true,
value: function ResizeObserverMock(): ResizeObserver {
return {
observe: noop,
unobserve: noop,
disconnect: noop
};
}
});
32 changes: 31 additions & 1 deletion src/mocks/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { matchRequestUrl, MockedRequest } from 'msw';
import { setupServer } from 'msw/node';
import { ServerLifecycleEventsMap, setupServer } from 'msw/node';

import handlers from './handlers';

Expand Down Expand Up @@ -38,3 +38,33 @@ export function waitForRequest(method: string, url: string): Promise<MockedReque
});
});
}

export function waitForResponse(
method: string,
url: string
): Promise<ServerLifecycleEventsMap['response:mocked'][0]> {
let requestId = '';

return new Promise((resolve, reject) => {
server.events.on('request:start', (req) => {
const matchesMethod = req.method.toLowerCase() === method.toLowerCase();
const matchesUrl = matchRequestUrl(req.url, url).matches;

if (matchesMethod && matchesUrl) {
requestId = req.id;
}
});

server.events.on('response:mocked', (res, reqId) => {
if (reqId === requestId) {
resolve(res);
}
});

server.events.on('request:unhandled', (req) => {
if (req.id === requestId) {
reject(new Error(`The ${req.method} ${req.url.href} request was unhandled.`));
}
});
});
}
2 changes: 0 additions & 2 deletions src/network/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import { type ErrorSoapResponse } from '../../types';
import { SHELL_APP_ID } from '../constants';
import server from '../mocks/server';

jest.mock<typeof import('../workers')>('../workers');

describe('Fetch', () => {
test('should redirect to login if user is not authenticated', async () => {
server.use(
Expand Down
2 changes: 1 addition & 1 deletion src/network/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
SoapResponse
} from '../../types';
import { userAgent } from './user-agent';
import { report } from '../reporting';
import { report } from '../reporting/functions';
import { useAccountStore } from '../store/account';
import { IS_STANDALONE, SHELL_APP_ID } from '../constants';
import { useNetworkStore } from '../store/network';
Expand Down
2 changes: 0 additions & 2 deletions src/network/get-components.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import { GetComponentsJsonResponseBody } from '../mocks/handlers/components';
import server from '../mocks/server';
import { useAppStore } from '../store/app';

jest.mock<typeof import('../workers')>('../workers');

describe('Get components', () => {
test('Setup apps and request data for the logged account', async () => {
const shellModule: CarbonioModule = {
Expand Down
7 changes: 0 additions & 7 deletions src/reporting/__mocks__/index.ts

This file was deleted.

7 changes: 0 additions & 7 deletions src/reporting/index.ts

This file was deleted.

Loading

0 comments on commit adaecfd

Please sign in to comment.