[Snapshot & Restore] Remove axios dependency in tests (#128614)

* wip: start refactoring test helpers

* commit using @elastic.co

* Fix more tests

* Finish off refactoring all cits

* Add docs

* Fix linter issues

* Fix ts issues
This commit is contained in:
Ignacio Rivas 2022-04-04 12:31:10 +02:00 committed by GitHub
parent d9153a620b
commit fa74030731
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 460 additions and 380 deletions

View file

@ -13,4 +13,6 @@ export const REPOSITORY_EDIT = getRepository({ name: REPOSITORY_NAME });
export const POLICY_NAME = 'my-test-policy';
export const SNAPSHOT_NAME = 'my-test-snapshot';
export const POLICY_EDIT = getPolicy({ name: POLICY_NAME, retention: { minCount: 1 } });

View file

@ -14,6 +14,7 @@ import {
AsyncTestBedConfig,
delay,
} from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { SnapshotRestoreHome } from '../../../public/application/sections/home/home';
import { BASE_PATH } from '../../../public/application/constants';
import { WithAppDependencies } from './setup_environment';
@ -26,8 +27,6 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};
const initTestBed = registerTestBed(WithAppDependencies(SnapshotRestoreHome), testBedConfig);
export interface HomeTestBed extends TestBed {
actions: {
clickReloadButton: () => void;
@ -40,7 +39,11 @@ export interface HomeTestBed extends TestBed {
};
}
export const setup = async (): Promise<HomeTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<HomeTestBed> => {
const initTestBed = registerTestBed(
WithAppDependencies(SnapshotRestoreHome, httpSetup),
testBedConfig
);
const testBed = await initTestBed();
const REPOSITORY_TABLE = 'repositoryTable';
const SNAPSHOT_TABLE = 'snapshotTable';

View file

@ -5,117 +5,119 @@
* 2.0.
*/
import sinon, { SinonFakeServer } from 'sinon';
import { httpServiceMock } from '../../../../../../src/core/public/mocks';
import { API_BASE_PATH } from '../../../common';
type HttpMethod = 'GET' | 'PUT' | 'POST';
type HttpResponse = Record<string, any> | any[];
const mockResponse = (defaultResponse: HttpResponse, response?: HttpResponse) => [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify({ ...defaultResponse, ...response }),
];
export interface ResponseError {
statusCode: number;
message: string | Error;
}
// Register helpers to mock HTTP Requests
const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
const setLoadRepositoriesResponse = (response: HttpResponse = {}) => {
const defaultResponse = { repositories: [] };
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>
) => {
const mockResponses = new Map<HttpMethod, Map<string, Promise<unknown>>>(
['GET', 'PUT', 'POST'].map(
(method) => [method, new Map()] as [HttpMethod, Map<string, Promise<unknown>>]
)
);
server.respondWith(
'GET',
`${API_BASE_PATH}repositories`,
mockResponse(defaultResponse, response)
);
const mockMethodImplementation = (method: HttpMethod, path: string) =>
mockResponses.get(method)?.get(path) ?? Promise.resolve({});
httpSetup.get.mockImplementation((path) =>
mockMethodImplementation('GET', path as unknown as string)
);
httpSetup.post.mockImplementation((path) =>
mockMethodImplementation('POST', path as unknown as string)
);
httpSetup.put.mockImplementation((path) =>
mockMethodImplementation('PUT', path as unknown as string)
);
const mockResponse = (method: HttpMethod, path: string, response?: unknown, error?: unknown) => {
const defuse = (promise: Promise<unknown>) => {
promise.catch(() => {});
return promise;
};
return mockResponses
.get(method)!
.set(path, error ? defuse(Promise.reject({ body: error })) : Promise.resolve(response));
};
const setLoadRepositoryTypesResponse = (response: HttpResponse = []) => {
server.respondWith('GET', `${API_BASE_PATH}repository_types`, JSON.stringify(response));
};
const setLoadRepositoriesResponse = (
response: HttpResponse = { repositories: [] },
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}repositories`, response, error);
const setGetRepositoryResponse = (response?: HttpResponse, delay = 0) => {
const defaultResponse = {};
const setLoadRepositoryTypesResponse = (response: HttpResponse = [], error?: ResponseError) =>
mockResponse('GET', `${API_BASE_PATH}repository_types`, response, error);
server.respondWith(
'GET',
/api\/snapshot_restore\/repositories\/.+/,
mockResponse(defaultResponse, response)
);
};
const setGetRepositoryResponse = (
repositoryName: string,
response?: HttpResponse,
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}repositories/${repositoryName}`, response, error);
const setSaveRepositoryResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);
const setSaveRepositoryResponse = (response?: HttpResponse, error?: ResponseError) =>
mockResponse('PUT', `${API_BASE_PATH}repositories`, response, error);
server.respondWith('PUT', `${API_BASE_PATH}repositories`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
const setLoadSnapshotsResponse = (response: HttpResponse = {}) => {
const setLoadSnapshotsResponse = (response?: HttpResponse, error?: ResponseError) => {
const defaultResponse = { errors: {}, snapshots: [], repositories: [], total: 0 };
server.respondWith('GET', `${API_BASE_PATH}snapshots`, mockResponse(defaultResponse, response));
return mockResponse('GET', `${API_BASE_PATH}snapshots`, response ?? defaultResponse, error);
};
const setGetSnapshotResponse = (response?: HttpResponse) => {
const defaultResponse = {};
server.respondWith(
const setGetSnapshotResponse = (
repositoryName: string,
snapshotName: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse(
'GET',
/\/api\/snapshot_restore\/snapshots\/.+/,
mockResponse(defaultResponse, response)
`${API_BASE_PATH}snapshots/${repositoryName}/${snapshotName}`,
response,
error
);
};
const setLoadIndicesResponse = (response: HttpResponse = {}) => {
const defaultResponse = { indices: [] };
const setLoadIndicesResponse = (
response: HttpResponse = { indices: [] },
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}policies/indices`, response, error);
server.respondWith(
'GET',
`${API_BASE_PATH}policies/indices`,
mockResponse(defaultResponse, response)
const setAddPolicyResponse = (response?: HttpResponse, error?: ResponseError) =>
mockResponse('POST', `${API_BASE_PATH}policies`, response, error);
const setCleanupRepositoryResponse = (
repositoryName: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse('POST', `${API_BASE_PATH}repositories/${repositoryName}/cleanup`, response, error);
const setGetPolicyResponse = (
policyName: string,
response?: HttpResponse,
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}policy/${policyName}`, response, error);
const setRestoreSnapshotResponse = (
repositoryName: string,
snapshotId: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse(
'POST',
`${API_BASE_PATH}restore/${repositoryName}/${snapshotId}`,
response,
error
);
};
const setAddPolicyResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);
server.respondWith('POST', `${API_BASE_PATH}policies`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
const setCleanupRepositoryResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 503 : 200;
const body = error ? JSON.stringify(error) : JSON.stringify(response);
server.respondWith('POST', `${API_BASE_PATH}repositories/:name/cleanup`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
const setGetPolicyResponse = (response?: HttpResponse) => {
server.respondWith('GET', `${API_BASE_PATH}policy/:name`, [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
};
const setRestoreSnapshotResponse = (response?: HttpResponse) => {
server.respondWith('POST', `${API_BASE_PATH}restore/:repository/:snapshot`, [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
};
return {
setLoadRepositoriesResponse,
@ -133,18 +135,11 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
};
export const init = () => {
const server = sinon.fakeServer.create();
server.respondImmediately = true;
// Define default response for unhandled requests.
// We make requests to APIs which don't impact the component under test, e.g. UI metric telemetry,
// and we can mock them all with a 200 instead of mocking each one individually.
server.respondWith([200, {}, 'DefaultResponse']);
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(server);
const httpSetup = httpServiceMock.createSetupContract();
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup);
return {
server,
httpSetup,
httpRequestsMockHelpers,
};
};

View file

@ -6,6 +6,7 @@
*/
import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PolicyAdd } from '../../../public/application/sections/policy_add';
import { formSetup, PolicyFormTestSubjects } from './policy_form.helpers';
import { WithAppDependencies } from './setup_environment';
@ -18,9 +19,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyAdd),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyAdd, httpSetup),
testBedConfig
);
export const setup = formSetup.bind(null, initTestBed);
return formSetup(initTestBed);
};

View file

@ -6,6 +6,7 @@
*/
import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PolicyEdit } from '../../../public/application/sections/policy_edit';
import { WithAppDependencies } from './setup_environment';
import { POLICY_NAME } from './constant';
@ -19,9 +20,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyEdit),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyEdit, httpSetup),
testBedConfig
);
export const setup = formSetup.bind(null, initTestBed);
return formSetup(initTestBed);
};

View file

@ -6,14 +6,11 @@
*/
import { registerTestBed, TestBed } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { RepositoryType } from '../../../common/types';
import { RepositoryAdd } from '../../../public/application/sections/repository_add';
import { WithAppDependencies } from './setup_environment';
const initTestBed = registerTestBed<RepositoryAddTestSubjects>(WithAppDependencies(RepositoryAdd), {
doMountAsync: true,
});
export interface RepositoryAddTestBed extends TestBed<RepositoryAddTestSubjects> {
actions: {
clickNextButton: () => void;
@ -23,7 +20,13 @@ export interface RepositoryAddTestBed extends TestBed<RepositoryAddTestSubjects>
};
}
export const setup = async (): Promise<RepositoryAddTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<RepositoryAddTestBed> => {
const initTestBed = registerTestBed<RepositoryAddTestSubjects>(
WithAppDependencies(RepositoryAdd, httpSetup),
{
doMountAsync: true,
}
);
const testBed = await initTestBed();
// User actions

View file

@ -6,6 +6,7 @@
*/
import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { RepositoryEdit } from '../../../public/application/sections/repository_edit';
import { WithAppDependencies } from './setup_environment';
import { REPOSITORY_NAME } from './constant';
@ -18,10 +19,14 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};
export const setup = registerTestBed<RepositoryEditTestSubjects>(
WithAppDependencies(RepositoryEdit),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<RepositoryEditTestSubjects>(
WithAppDependencies(RepositoryEdit, httpSetup),
testBedConfig
);
return await initTestBed();
};
export type RepositoryEditTestSubjects = TestSubjects | ThreeLevelDepth | NonVisibleTestSubjects;

View file

@ -6,23 +6,20 @@
*/
import { act } from 'react-dom/test-utils';
import { HttpSetup } from 'src/core/public';
import { registerTestBed, TestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { RestoreSnapshot } from '../../../public/application/sections/restore_snapshot';
import { WithAppDependencies } from './setup_environment';
import { REPOSITORY_NAME, SNAPSHOT_NAME } from '../helpers/constant';
const testBedConfig: AsyncTestBedConfig = {
memoryRouter: {
initialEntries: ['/add_policy'],
componentRoutePath: '/add_policy',
initialEntries: [`/restore/${REPOSITORY_NAME}/${SNAPSHOT_NAME}`],
componentRoutePath: '/restore/:repositoryName?/:snapshotId*',
},
doMountAsync: true,
};
const initTestBed = registerTestBed<RestoreSnapshotFormTestSubject>(
WithAppDependencies(RestoreSnapshot),
testBedConfig
);
const setupActions = (testBed: TestBed<RestoreSnapshotFormTestSubject>) => {
const { find, component, form, exists } = testBed;
@ -84,7 +81,12 @@ export type RestoreSnapshotTestBed = TestBed<RestoreSnapshotFormTestSubject> & {
actions: Actions;
};
export const setup = async (): Promise<RestoreSnapshotTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<RestoreSnapshotTestBed> => {
const initTestBed = registerTestBed<RestoreSnapshotFormTestSubject>(
WithAppDependencies(RestoreSnapshot, httpSetup),
testBedConfig
);
const testBed = await initTestBed();
return {

View file

@ -6,11 +6,10 @@
*/
import React from 'react';
import axios from 'axios';
import axiosXhrAdapter from 'axios/lib/adapters/xhr';
import { i18n } from '@kbn/i18n';
import { LocationDescriptorObject } from 'history';
import { HttpSetup } from 'src/core/public';
import { coreMock, scopedHistoryMock } from 'src/core/public/mocks';
import { setUiMetricService, httpService } from '../../../public/application/services/http';
import {
@ -22,8 +21,6 @@ import { textService } from '../../../public/application/services/text';
import { init as initHttpRequests } from './http_requests';
import { UiMetricService } from '../../../public/application/services';
const mockHttpClient = axios.create({ adapter: axiosXhrAdapter });
const history = scopedHistoryMock.create();
history.createHref.mockImplementation((location: LocationDescriptorObject) => {
return `${location.pathname}?${location.search}`;
@ -48,18 +45,11 @@ const appDependencies = {
};
export const setupEnvironment = () => {
// @ts-ignore
httpService.setup(mockHttpClient);
breadcrumbService.setup(() => undefined);
textService.setup(i18n);
docTitleService.setup(() => undefined);
const { server, httpRequestsMockHelpers } = initHttpRequests();
return {
server,
httpRequestsMockHelpers,
};
return initHttpRequests();
};
/**
@ -70,9 +60,16 @@ export const setupEnvironment = () => {
this.terminate = () => {};
};
export const WithAppDependencies = (Comp: any) => (props: any) =>
(
export const WithAppDependencies = (Comp: any, httpSetup?: HttpSetup) => (props: any) => {
// We need to optionally setup the httpService since some cit helpers (such as snapshot_list.helpers)
// use jest mocks to stub the fetch hooks instead of mocking api responses.
if (httpSetup) {
httpService.setup(httpSetup);
}
return (
<AppContextProvider value={appDependencies as any}>
<Comp {...props} />
</AppContextProvider>
);
};

View file

@ -35,6 +35,7 @@ const searchErrorSelector = 'snapshotListSearchError';
export const setup = async (query?: string): Promise<SnapshotListTestBed> => {
const testBed = await initTestBed(query);
const { form, component, find, exists } = testBed;
const setSearchText = async (value: string, advanceTime = true) => {

View file

@ -41,16 +41,12 @@ const removeWhiteSpaceOnArrayValues = (array: any[]) =>
});
describe('<SnapshotRestoreHome />', () => {
const { server, httpRequestsMockHelpers } = setupEnvironment();
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
let testBed: HomeTestBed;
afterAll(() => {
server.restore();
});
describe('on component mount', () => {
beforeEach(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
test('should set the correct app title', () => {
@ -79,7 +75,7 @@ describe('<SnapshotRestoreHome />', () => {
describe('tabs', () => {
beforeEach(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -132,7 +128,7 @@ describe('<SnapshotRestoreHome />', () => {
});
test('should display an empty prompt', async () => {
const { component, exists } = await setup();
const { component, exists } = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -164,7 +160,7 @@ describe('<SnapshotRestoreHome />', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoriesResponse({ repositories });
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -208,7 +204,6 @@ describe('<SnapshotRestoreHome />', () => {
test('should have a button to reload the repositories', async () => {
const { component, exists, actions } = testBed;
const totalRequests = server.requests.length;
expect(exists('reloadButton')).toBe(true);
await act(async () => {
@ -217,9 +212,9 @@ describe('<SnapshotRestoreHome />', () => {
component.update();
});
expect(server.requests.length).toBe(totalRequests + 1);
expect(server.requests[server.requests.length - 1].url).toBe(
`${API_BASE_PATH}repositories`
expect(httpSetup.get).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.anything()
);
});
@ -273,10 +268,10 @@ describe('<SnapshotRestoreHome />', () => {
component.update();
});
const latestRequest = server.requests[server.requests.length - 1];
expect(latestRequest.method).toBe('DELETE');
expect(latestRequest.url).toBe(`${API_BASE_PATH}repositories/${repo1.name}`);
expect(httpSetup.delete).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories/${repo1.name}`,
expect.anything()
);
});
});
@ -304,23 +299,20 @@ describe('<SnapshotRestoreHome />', () => {
});
test('should show a loading state while fetching the repository', async () => {
server.respondImmediately = false;
const { find, exists, actions } = testBed;
// By providing undefined, the "loading section" will be displayed
httpRequestsMockHelpers.setGetRepositoryResponse(undefined);
httpRequestsMockHelpers.setGetRepositoryResponse(repo1.name, undefined);
await actions.clickRepositoryAt(0);
expect(exists('repositoryDetail.sectionLoading')).toBe(true);
expect(find('repositoryDetail.sectionLoading').text()).toEqual('Loading repository…');
server.respondImmediately = true;
});
describe('when the repository has been fetched', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetRepositoryResponse({
httpRequestsMockHelpers.setGetRepositoryResponse(repo1.name, {
repository: {
name: 'my-repo',
type: 'fs',
@ -357,15 +349,15 @@ describe('<SnapshotRestoreHome />', () => {
component.update();
});
const latestRequest = server.requests[server.requests.length - 1];
expect(latestRequest.method).toBe('GET');
expect(latestRequest.url).toBe(`${API_BASE_PATH}repositories/${repo1.name}/verify`);
expect(httpSetup.get).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories/${repo1.name}/verify`,
expect.anything()
);
});
describe('clean repository', () => {
test('shows results when request succeeds', async () => {
httpRequestsMockHelpers.setCleanupRepositoryResponse({
httpRequestsMockHelpers.setCleanupRepositoryResponse(repo1.name, {
cleanup: {
cleaned: true,
response: {
@ -383,16 +375,17 @@ describe('<SnapshotRestoreHome />', () => {
});
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(latestRequest.method).toBe('POST');
expect(latestRequest.url).toBe(`${API_BASE_PATH}repositories/${repo1.name}/cleanup`);
expect(httpSetup.post).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories/${repo1.name}/cleanup`,
expect.anything()
);
expect(exists('repositoryDetail.cleanupCodeBlock')).toBe(true);
expect(exists('repositoryDetail.cleanupError')).toBe(false);
});
test('shows error when success fails', async () => {
httpRequestsMockHelpers.setCleanupRepositoryResponse({
httpRequestsMockHelpers.setCleanupRepositoryResponse(repo1.name, {
cleanup: {
cleaned: false,
error: {
@ -408,9 +401,10 @@ describe('<SnapshotRestoreHome />', () => {
});
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(latestRequest.method).toBe('POST');
expect(latestRequest.url).toBe(`${API_BASE_PATH}repositories/${repo1.name}/cleanup`);
expect(httpSetup.post).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories/${repo1.name}/cleanup`,
expect.anything()
);
expect(exists('repositoryDetail.cleanupCodeBlock')).toBe(false);
expect(exists('repositoryDetail.cleanupError')).toBe(true);
@ -420,7 +414,7 @@ describe('<SnapshotRestoreHome />', () => {
describe('when the repository has been fetched (and has snapshots)', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetRepositoryResponse({
httpRequestsMockHelpers.setGetRepositoryResponse(repo1.name, {
repository: {
name: 'my-repo',
type: 'fs',
@ -448,7 +442,7 @@ describe('<SnapshotRestoreHome />', () => {
});
beforeEach(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
testBed.actions.selectTab('snapshots');
@ -478,7 +472,7 @@ describe('<SnapshotRestoreHome />', () => {
total: 0,
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
testBed.actions.selectTab('snapshots');
@ -517,7 +511,7 @@ describe('<SnapshotRestoreHome />', () => {
total: 2,
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
testBed.actions.selectTab('snapshots');
@ -561,7 +555,7 @@ describe('<SnapshotRestoreHome />', () => {
},
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
testBed.actions.selectTab('snapshots');
@ -589,7 +583,7 @@ describe('<SnapshotRestoreHome />', () => {
},
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
testBed.actions.selectTab('snapshots');
@ -625,7 +619,6 @@ describe('<SnapshotRestoreHome />', () => {
test('should have a button to reload the snapshots', async () => {
const { component, exists, actions } = testBed;
const totalRequests = server.requests.length;
expect(exists('reloadButton')).toBe(true);
await act(async () => {
@ -634,13 +627,19 @@ describe('<SnapshotRestoreHome />', () => {
component.update();
});
expect(server.requests.length).toBe(totalRequests + 1);
expect(server.requests[server.requests.length - 1].url).toBe(`${API_BASE_PATH}snapshots`);
expect(httpSetup.get).toHaveBeenLastCalledWith(
`${API_BASE_PATH}snapshots`,
expect.anything()
);
});
describe('detail panel', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(snapshot1);
httpRequestsMockHelpers.setGetSnapshotResponse(
snapshot1.repository,
snapshot1.snapshot,
snapshot1
);
});
test('should show the detail when clicking on a snapshot', async () => {
@ -656,17 +655,18 @@ describe('<SnapshotRestoreHome />', () => {
// that makes the component crash. I tried a few things with no luck so, as this
// is a low impact test, I prefer to skip it and move on.
test.skip('should show a loading while fetching the snapshot', async () => {
server.respondImmediately = false;
const { find, exists, actions } = testBed;
// By providing undefined, the "loading section" will be displayed
httpRequestsMockHelpers.setGetSnapshotResponse(undefined);
httpRequestsMockHelpers.setGetSnapshotResponse(
snapshot1.repository,
snapshot1.snapshot,
undefined
);
await actions.clickSnapshotAt(0);
expect(exists('snapshotDetail.sectionLoading')).toBe(true);
expect(find('snapshotDetail.sectionLoading').text()).toEqual('Loading snapshot…');
server.respondImmediately = true;
});
describe('on mount', () => {
@ -757,7 +757,11 @@ describe('<SnapshotRestoreHome />', () => {
const setSnapshotStateAndUpdateDetail = async (state: string) => {
const updatedSnapshot = { ...snapshot1, state };
httpRequestsMockHelpers.setGetSnapshotResponse(updatedSnapshot);
httpRequestsMockHelpers.setGetSnapshotResponse(
itemIndexToClickOn === 0 ? snapshot1.repository : snapshot2.repository,
itemIndexToClickOn === 0 ? snapshot1.snapshot : snapshot2.snapshot,
updatedSnapshot
);
await actions.clickSnapshotAt(itemIndexToClickOn); // click another snapshot to trigger the HTTP call
};
@ -787,9 +791,12 @@ describe('<SnapshotRestoreHome />', () => {
};
// Call sequentially each state and verify that the message is ok
return Object.entries(mapStateToMessage).reduce((promise, [state, message]) => {
return promise.then(async () => expectMessageForSnapshotState(state, message));
}, Promise.resolve());
return Object.entries(mapStateToMessage).reduce(
async (promise, [state, message]) => {
return promise.then(async () => expectMessageForSnapshotState(state, message));
},
Promise.resolve()
);
});
});
@ -805,8 +812,12 @@ describe('<SnapshotRestoreHome />', () => {
test('should display a message when snapshot in progress ', async () => {
const { find, actions } = testBed;
const updatedSnapshot = { ...snapshot1, state: 'IN_PROGRESS' };
httpRequestsMockHelpers.setGetSnapshotResponse(updatedSnapshot);
const updatedSnapshot = { ...snapshot2, state: 'IN_PROGRESS' };
httpRequestsMockHelpers.setGetSnapshotResponse(
snapshot2.repository,
snapshot2.snapshot,
updatedSnapshot
);
await actions.clickSnapshotAt(1); // click another snapshot to trigger the HTTP call
actions.selectSnapshotDetailTab('failedIndices');
@ -825,7 +836,11 @@ describe('<SnapshotRestoreHome />', () => {
beforeEach(async () => {
const updatedSnapshot = { ...snapshot1, indexFailures };
httpRequestsMockHelpers.setGetSnapshotResponse(updatedSnapshot);
httpRequestsMockHelpers.setGetSnapshotResponse(
updatedSnapshot.repository,
updatedSnapshot.snapshot,
updatedSnapshot
);
await testBed.actions.clickSnapshotAt(0);
testBed.actions.selectSnapshotDetailTab('failedIndices');
});

View file

@ -12,6 +12,7 @@ import { ReactElement } from 'react';
import { act } from 'react-dom/test-utils';
import * as fixtures from '../../test/fixtures';
import { API_BASE_PATH } from '../../common';
import { PolicyFormTestBed } from './helpers/policy_form.helpers';
import { DEFAULT_POLICY_SCHEDULE } from '../../public/application/constants';
@ -36,12 +37,7 @@ const repository = fixtures.getRepository({ name: `a${getRandomString()}`, type:
describe('<PolicyAdd />', () => {
let testBed: PolicyFormTestBed;
const { server, httpRequestsMockHelpers } = setupEnvironment();
afterAll(() => {
server.restore();
});
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
describe('on component mount', () => {
beforeEach(async () => {
@ -51,7 +47,7 @@ describe('<PolicyAdd />', () => {
dataStreams: ['my_data_stream', 'my_other_data_stream'],
});
testBed = await setup();
testBed = await setup(httpSetup);
await nextTick();
testBed.component.update();
});
@ -241,36 +237,37 @@ describe('<PolicyAdd />', () => {
await nextTick();
});
const latestRequest = server.requests[server.requests.length - 1];
const expected = {
config: {},
isManagedPolicy: false,
name: POLICY_NAME,
repository: repository.name,
retention: {
expireAfterUnit: 'd', // default
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
maxCount: Number(MAX_COUNT),
minCount: Number(MIN_COUNT),
},
schedule: DEFAULT_POLICY_SCHEDULE,
snapshotName: SNAPSHOT_NAME,
};
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual(expected);
expect(httpSetup.post).toHaveBeenLastCalledWith(
`${API_BASE_PATH}policies`,
expect.objectContaining({
body: JSON.stringify({
name: POLICY_NAME,
snapshotName: SNAPSHOT_NAME,
schedule: DEFAULT_POLICY_SCHEDULE,
repository: repository.name,
config: {},
retention: {
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
expireAfterUnit: 'd', // default
maxCount: Number(MAX_COUNT),
minCount: Number(MIN_COUNT),
},
isManagedPolicy: false,
}),
})
);
});
it('should surface the API errors from the put HTTP request', async () => {
const { component, actions, find, exists } = testBed;
const error = {
status: 409,
statusCode: 409,
error: 'Conflict',
message: `There is already a policy with name '${POLICY_NAME}'`,
};
httpRequestsMockHelpers.setAddPolicyResponse(undefined, { body: error });
httpRequestsMockHelpers.setAddPolicyResponse(undefined, error);
await act(async () => {
actions.clickSubmitButton();

View file

@ -8,6 +8,7 @@
import { act } from 'react-dom/test-utils';
import { setupEnvironment, pageHelpers, nextTick } from './helpers';
import { API_BASE_PATH } from '../../common';
import { PolicyForm } from '../../public/application/components/policy_form';
import { PolicyFormTestBed } from './helpers/policy_form.helpers';
import { POLICY_EDIT } from './helpers/constant';
@ -22,15 +23,11 @@ const EXPIRE_AFTER_UNIT = TIME_UNITS.MINUTE;
describe('<PolicyEdit />', () => {
let testBed: PolicyFormTestBed;
let testBedPolicyAdd: PolicyFormTestBed;
const { server, httpRequestsMockHelpers } = setupEnvironment();
afterAll(() => {
server.restore();
});
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
describe('on component mount', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetPolicyResponse({ policy: POLICY_EDIT });
httpRequestsMockHelpers.setGetPolicyResponse(POLICY_EDIT.name, { policy: POLICY_EDIT });
httpRequestsMockHelpers.setLoadIndicesResponse({
indices: ['my_index'],
dataStreams: ['my_data_stream'],
@ -39,7 +36,7 @@ describe('<PolicyEdit />', () => {
repositories: [{ name: POLICY_EDIT.repository }],
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -55,7 +52,7 @@ describe('<PolicyEdit />', () => {
describe('policy with pre-existing repository that was deleted', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetPolicyResponse({ policy: POLICY_EDIT });
httpRequestsMockHelpers.setGetPolicyResponse(POLICY_EDIT.name, { policy: POLICY_EDIT });
httpRequestsMockHelpers.setLoadIndicesResponse({
indices: ['my_index'],
dataStreams: ['my_data_stream'],
@ -64,7 +61,7 @@ describe('<PolicyEdit />', () => {
repositories: [{ name: 'this-is-a-new-repository' }],
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -97,7 +94,7 @@ describe('<PolicyEdit />', () => {
* the same form component is indeed shared between the 2 app sections.
*/
test('should use the same Form component as the "<PolicyAdd />" section', async () => {
testBedPolicyAdd = await setupPolicyAdd();
testBedPolicyAdd = await setupPolicyAdd(httpSetup);
await act(async () => {
await nextTick();
@ -143,27 +140,28 @@ describe('<PolicyEdit />', () => {
await nextTick();
});
const latestRequest = server.requests[server.requests.length - 1];
const { name, isManagedPolicy, schedule, repository, retention } = POLICY_EDIT;
const expected = {
name,
isManagedPolicy,
schedule,
repository,
config: {
ignoreUnavailable: true,
},
retention: {
...retention,
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
expireAfterUnit: EXPIRE_AFTER_UNIT,
},
snapshotName: editedSnapshotName,
};
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual(expected);
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}policies/${name}`,
expect.objectContaining({
body: JSON.stringify({
name,
snapshotName: editedSnapshotName,
schedule,
repository,
config: {
ignoreUnavailable: true,
},
retention: {
...retention,
expireAfterUnit: EXPIRE_AFTER_UNIT,
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
},
isManagedPolicy,
}),
})
);
});
it('should provide a default time unit value for retention', async () => {
@ -184,25 +182,27 @@ describe('<PolicyEdit />', () => {
await nextTick();
});
const latestRequest = server.requests[server.requests.length - 1];
const { name, isManagedPolicy, schedule, repository, retention, config, snapshotName } =
POLICY_EDIT;
const expected = {
name,
isManagedPolicy,
schedule,
repository,
config,
snapshotName,
retention: {
...retention,
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
expireAfterUnit: TIME_UNITS.DAY, // default value
},
};
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual(expected);
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}policies/${name}`,
expect.objectContaining({
body: JSON.stringify({
name,
snapshotName,
schedule,
repository,
config,
retention: {
...retention,
expireAfterUnit: TIME_UNITS.DAY, // default value
expireAfterValue: Number(EXPIRE_AFTER_VALUE),
},
isManagedPolicy,
}),
})
);
});
});
});

View file

@ -8,6 +8,7 @@
import { act } from 'react-dom/test-utils';
import { INVALID_NAME_CHARS } from '../../public/application/services/validation/validate_repository';
import { API_BASE_PATH } from '../../common';
import { getRepository } from '../../test/fixtures';
import { RepositoryType } from '../../common/types';
import { setupEnvironment, pageHelpers, nextTick, delay } from './helpers';
@ -18,18 +19,13 @@ const repositoryTypes = ['fs', 'url', 'source', 'azure', 'gcs', 's3', 'hdfs'];
describe('<RepositoryAdd />', () => {
let testBed: RepositoryAddTestBed;
const { server, httpRequestsMockHelpers } = setupEnvironment();
afterAll(() => {
server.restore();
});
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
describe('on component mount', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse(repositoryTypes);
testBed = await setup();
testBed = await setup(httpSetup);
});
test('should set the correct page title', () => {
@ -65,7 +61,7 @@ describe('<RepositoryAdd />', () => {
describe('when no repository types are not found', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse([]);
testBed = await setup();
testBed = await setup(httpSetup);
await nextTick();
testBed.component.update();
});
@ -81,7 +77,7 @@ describe('<RepositoryAdd />', () => {
describe('when repository types are found', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse(repositoryTypes);
testBed = await setup();
testBed = await setup(httpSetup);
await nextTick();
testBed.component.update();
});
@ -104,7 +100,7 @@ describe('<RepositoryAdd />', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse(repositoryTypes);
testBed = await setup();
testBed = await setup(httpSetup);
await nextTick();
testBed.component.update();
});
@ -205,7 +201,7 @@ describe('<RepositoryAdd />', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse(repositoryTypes);
testBed = await setup();
testBed = await setup(httpSetup);
});
describe('not source only', () => {
@ -231,17 +227,23 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: fsRepository.name,
type: fsRepository.type,
settings: {
...fsRepository.settings,
compress: true,
readonly: true,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: fsRepository.name,
type: fsRepository.type,
settings: {
location: fsRepository.settings.location,
compress: true,
chunkSize: fsRepository.settings.chunkSize,
maxSnapshotBytesPerSec: fsRepository.settings.maxSnapshotBytesPerSec,
maxRestoreBytesPerSec: fsRepository.settings.maxRestoreBytesPerSec,
readonly: true,
},
}),
})
);
});
test('should send the correct payload for Azure repository', async () => {
@ -283,17 +285,25 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: azureRepository.name,
type: azureRepository.type,
settings: {
...azureRepository.settings,
compress: false,
readonly: true,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: azureRepository.name,
type: azureRepository.type,
settings: {
client: azureRepository.settings.client,
container: azureRepository.settings.container,
basePath: azureRepository.settings.basePath,
compress: false,
chunkSize: azureRepository.settings.chunkSize,
maxSnapshotBytesPerSec: azureRepository.settings.maxSnapshotBytesPerSec,
maxRestoreBytesPerSec: azureRepository.settings.maxRestoreBytesPerSec,
readonly: true,
},
}),
})
);
});
test('should send the correct payload for GCS repository', async () => {
@ -332,17 +342,25 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: gcsRepository.name,
type: gcsRepository.type,
settings: {
...gcsRepository.settings,
compress: false,
readonly: true,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: gcsRepository.name,
type: gcsRepository.type,
settings: {
client: gcsRepository.settings.client,
bucket: gcsRepository.settings.bucket,
basePath: gcsRepository.settings.basePath,
compress: false,
chunkSize: gcsRepository.settings.chunkSize,
maxSnapshotBytesPerSec: gcsRepository.settings.maxSnapshotBytesPerSec,
maxRestoreBytesPerSec: gcsRepository.settings.maxRestoreBytesPerSec,
readonly: true,
},
}),
})
);
});
test('should send the correct payload for HDFS repository', async () => {
@ -379,18 +397,24 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: hdfsRepository.name,
type: hdfsRepository.type,
settings: {
...hdfsRepository.settings,
uri: `hdfs://${hdfsRepository.settings.uri}`,
compress: false,
readonly: true,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: hdfsRepository.name,
type: hdfsRepository.type,
settings: {
uri: `hdfs://${hdfsRepository.settings.uri}`,
path: hdfsRepository.settings.path,
compress: false,
chunkSize: hdfsRepository.settings.chunkSize,
maxSnapshotBytesPerSec: hdfsRepository.settings.maxSnapshotBytesPerSec,
maxRestoreBytesPerSec: hdfsRepository.settings.maxRestoreBytesPerSec,
readonly: true,
},
}),
})
);
});
test('should send the correct payload for S3 repository', async () => {
@ -431,17 +455,26 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: s3Repository.name,
type: s3Repository.type,
settings: {
...s3Repository.settings,
compress: false,
readonly: true,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: s3Repository.name,
type: s3Repository.type,
settings: {
bucket: s3Repository.settings.bucket,
client: s3Repository.settings.client,
basePath: s3Repository.settings.basePath,
bufferSize: s3Repository.settings.bufferSize,
compress: false,
chunkSize: s3Repository.settings.chunkSize,
maxSnapshotBytesPerSec: s3Repository.settings.maxSnapshotBytesPerSec,
maxRestoreBytesPerSec: s3Repository.settings.maxRestoreBytesPerSec,
readonly: true,
},
}),
})
);
});
test('should surface the API errors from the "save" HTTP request', async () => {
@ -457,12 +490,12 @@ describe('<RepositoryAdd />', () => {
form.toggleEuiSwitch('compressToggle');
const error = {
status: 400,
statusCode: 400,
error: 'Bad request',
message: 'Repository payload is invalid',
};
httpRequestsMockHelpers.setSaveRepositoryResponse(undefined, { body: error });
httpRequestsMockHelpers.setSaveRepositoryResponse(undefined, error);
await act(async () => {
actions.clickSubmitButton();
@ -496,16 +529,19 @@ describe('<RepositoryAdd />', () => {
component.update();
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual({
name: fsRepository.name,
type: 'source',
settings: {
delegateType: fsRepository.type,
location: fsRepository.settings.location,
},
});
expect(httpSetup.put).toHaveBeenLastCalledWith(
`${API_BASE_PATH}repositories`,
expect.objectContaining({
body: JSON.stringify({
name: fsRepository.name,
type: 'source',
settings: {
delegateType: fsRepository.type,
location: fsRepository.settings.location,
},
}),
})
);
});
});
});

View file

@ -11,7 +11,7 @@ import { setupEnvironment, pageHelpers, nextTick, TestBed, getRandomString } fro
import { RepositoryForm } from '../../public/application/components/repository_form';
import { RepositoryEditTestSubjects } from './helpers/repository_edit.helpers';
import { RepositoryAddTestSubjects } from './helpers/repository_add.helpers';
import { REPOSITORY_EDIT } from './helpers/constant';
import { REPOSITORY_EDIT, REPOSITORY_NAME } from './helpers/constant';
const { setup } = pageHelpers.repositoryEdit;
const { setup: setupRepositoryAdd } = pageHelpers.repositoryAdd;
@ -19,19 +19,15 @@ const { setup: setupRepositoryAdd } = pageHelpers.repositoryAdd;
describe('<RepositoryEdit />', () => {
let testBed: TestBed<RepositoryEditTestSubjects>;
let testBedRepositoryAdd: TestBed<RepositoryAddTestSubjects>;
const { server, httpRequestsMockHelpers } = setupEnvironment();
afterAll(() => {
server.restore();
});
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
describe('on component mount', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetRepositoryResponse({
httpRequestsMockHelpers.setGetRepositoryResponse(REPOSITORY_EDIT.name, {
repository: REPOSITORY_EDIT,
snapshots: { count: 0 },
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();
@ -54,7 +50,7 @@ describe('<RepositoryEdit />', () => {
test('should use the same Form component as the "<RepositoryAdd />" section', async () => {
httpRequestsMockHelpers.setLoadRepositoryTypesResponse(['fs', 'url']);
testBedRepositoryAdd = await setupRepositoryAdd();
testBedRepositoryAdd = await setupRepositoryAdd(httpSetup);
const formEdit = testBed.component.find(RepositoryForm);
const formAdd = testBedRepositoryAdd.component.find(RepositoryForm);
@ -66,11 +62,11 @@ describe('<RepositoryEdit />', () => {
describe('should populate the correct values', () => {
const mountComponentWithMock = async (repository: any) => {
httpRequestsMockHelpers.setGetRepositoryResponse({
httpRequestsMockHelpers.setGetRepositoryResponse(REPOSITORY_NAME, {
repository: { name: getRandomString(), ...repository },
snapshots: { count: 0 },
});
testBed = await setup();
testBed = await setup(httpSetup);
await act(async () => {
await nextTick();

View file

@ -6,8 +6,10 @@
*/
import { act } from 'react-dom/test-utils';
import { API_BASE_PATH } from '../../common';
import { pageHelpers, setupEnvironment } from './helpers';
import { RestoreSnapshotTestBed } from './helpers/restore_snapshot.helpers';
import { REPOSITORY_NAME, SNAPSHOT_NAME } from './helpers/constant';
import * as fixtures from '../../test/fixtures';
const {
@ -15,19 +17,19 @@ const {
} = pageHelpers;
describe('<RestoreSnapshot />', () => {
const { server, httpRequestsMockHelpers } = setupEnvironment();
const { httpSetup, httpRequestsMockHelpers } = setupEnvironment();
let testBed: RestoreSnapshotTestBed;
afterAll(() => {
server.restore();
});
describe('wizard navigation', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(fixtures.getSnapshot());
httpRequestsMockHelpers.setGetSnapshotResponse(
REPOSITORY_NAME,
SNAPSHOT_NAME,
fixtures.getSnapshot()
);
await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
testBed.component.update();
@ -44,10 +46,14 @@ describe('<RestoreSnapshot />', () => {
describe('with data streams', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(fixtures.getSnapshot());
httpRequestsMockHelpers.setGetSnapshotResponse(
REPOSITORY_NAME,
SNAPSHOT_NAME,
fixtures.getSnapshot()
);
await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
testBed.component.update();
@ -61,9 +67,13 @@ describe('<RestoreSnapshot />', () => {
describe('without data streams', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(fixtures.getSnapshot({ totalDataStreams: 0 }));
httpRequestsMockHelpers.setGetSnapshotResponse(
REPOSITORY_NAME,
SNAPSHOT_NAME,
fixtures.getSnapshot({ totalDataStreams: 0 })
);
await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
testBed.component.update();
@ -77,9 +87,13 @@ describe('<RestoreSnapshot />', () => {
describe('global state', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(fixtures.getSnapshot());
httpRequestsMockHelpers.setGetSnapshotResponse(
REPOSITORY_NAME,
SNAPSHOT_NAME,
fixtures.getSnapshot()
);
await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
testBed.component.update();
@ -100,11 +114,14 @@ describe('<RestoreSnapshot />', () => {
// the form controls and asserting that the correct payload is sent to the API.
describe('include aliases', () => {
beforeEach(async () => {
httpRequestsMockHelpers.setGetSnapshotResponse(fixtures.getSnapshot());
httpRequestsMockHelpers.setRestoreSnapshotResponse({});
httpRequestsMockHelpers.setGetSnapshotResponse(
REPOSITORY_NAME,
SNAPSHOT_NAME,
fixtures.getSnapshot()
);
await act(async () => {
testBed = await setup();
testBed = await setup(httpSetup);
});
testBed.component.update();
@ -116,9 +133,14 @@ describe('<RestoreSnapshot />', () => {
actions.goToStep(3);
await actions.clickRestore();
const expectedPayload = { includeAliases: false };
const latestRequest = server.requests[server.requests.length - 1];
expect(JSON.parse(JSON.parse(latestRequest.requestBody).body)).toEqual(expectedPayload);
expect(httpSetup.post).toHaveBeenLastCalledWith(
`${API_BASE_PATH}restore/${REPOSITORY_NAME}/${SNAPSHOT_NAME}`,
expect.objectContaining({
body: JSON.stringify({
includeAliases: false,
}),
})
);
});
});
});