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

chore(tests): Add credentials table test #408

Merged
merged 13 commits into from
Apr 26, 2022
2 changes: 2 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ The decision to mock out a component during testing should adhere to RTL's guidi

* Make sure to import the component under test last. In Jest, any `jest.mock` calls are automatically hoisted to the top of the file, above the imports. This ensures that when modules are imported, Jest knows to replace the real implementations with the mocked versions. However, the actual mock implementation code isn’t processed until the component under test is imported, which is why it’s important to do this import last so that any imported modules used inside the implementations will not end up undefined.

* If you want to use mocked variables defined outside the scope of the `jest.mock` definition, you will need to import your components under test after the `jest.mock` call to prevent Jest from invoking the `jest.mock` calls before your variable is defined. For example, if you are mocking the `Api.Service` with `jest.mock` for your component under test called `MyComponent`, you will need to move `import { MyComponent } from '@app/Path/To/MyComponent';` as well as `import { ServiceContext, defaultServices } from '@app/Shared/Services/Services';` after all of your `jest.mock` calls.

* Use [`jest.requireActual`](https://jestjs.io/docs/jest-object#jestrequireactualmodulename) when you need the actual implementation of a mocked module. It can also be used to partially mock modules, allowing you to pick and choose which functions you want to mock or leave untouched.

* Unlike `jest.mock`, [`jest.doMock`](https://jestjs.io/docs/jest-object#jestdomockmodulename-factory-options) calls are not hoisted to the top of files. This is useful for when you want to mock a module differently across tests in the same file.
Expand Down
4 changes: 2 additions & 2 deletions src/app/SecurityPanel/SecurityPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@
import * as React from 'react';
import { Card, CardBody, CardTitle, Text, TextVariants } from '@patternfly/react-core';
import { BreadcrumbPage } from '@app/BreadcrumbPage/BreadcrumbPage';
import { StoreJmxCredentials } from './StoreJmxCredentials';
import { StoreJmxCredentialsCard } from './StoreJmxCredentials';
import { ImportCertificate } from './ImportCertificate';

export const SecurityPanel = () => {
const securityCards = [ImportCertificate, StoreJmxCredentials].map((c) => ({
const securityCards = [ImportCertificate, StoreJmxCredentialsCard].map((c) => ({
title: c.title,
description: c.description,
element: React.createElement(c.content, null),
Expand Down
8 changes: 4 additions & 4 deletions src/app/SecurityPanel/StoreJmxCredentials.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ import { SecurityCard } from './SecurityPanel';
import { NotificationCategory } from '@app/Shared/Services/NotificationChannel.service';
import { LoadingView } from '@app/LoadingView/LoadingView';

const Component = () => {
export const StoreJmxCredentials = () => {
const context = React.useContext(ServiceContext);
const addSubscription = useSubscriptions();

Expand Down Expand Up @@ -197,7 +197,7 @@ const Component = () => {
);
};
const targetRows = React.useMemo(() => {
return storedTargets.map((t, idx) => <TargetCredentialsTableRow key={idx} target={t} index={idx} />);
return storedTargets.map((t: Target, idx) => <TargetCredentialsTableRow key={idx} target={t} index={idx} />);
}, [storedTargets, checkedIndices]);

let content: JSX.Element;
Expand Down Expand Up @@ -243,10 +243,10 @@ const Component = () => {
</>);
};

export const StoreJmxCredentials: SecurityCard = {
export const StoreJmxCredentialsCard: SecurityCard = {
title: 'Store JMX Credentials',
description: `Targets for which Cryostat has stored JMX credentials are listed here.
If a Target JVM requires JMX authentication, Cryostat will use stored credentials
when attempting to open JMX connections to the target.`,
content: Component,
content: StoreJmxCredentials,
};
256 changes: 256 additions & 0 deletions src/test/SecurityPanel/StoreJmxCredentials.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import * as React from 'react';
import userEvent from '@testing-library/user-event';
import renderer, { act } from 'react-test-renderer';
import { render, screen } from '@testing-library/react';
import { of } from 'rxjs';
import { Target } from '@app/Shared/Services/Target.service';

import '@testing-library/jest-dom';
import { Modal, ModalVariant } from '@patternfly/react-core';
import { NotificationMessage } from '@app/Shared/Services/NotificationChannel.service';

const mockTarget: Target = { connectUrl: 'service:jmx:rmi://someUrl', alias: 'fooTarget' };
const mockAnotherTarget: Target = { connectUrl: 'service:jmx:rmi://anotherUrl', alias: 'anotherTarget' };

jest.mock('@app/SecurityPanel/CreateJmxCredentialModal', () => {
return {
CreateJmxCredentialModal: jest.fn((props) => {
return (
<Modal
isOpen={props.visible}
variant={ModalVariant.large}
showClose={true}
onClose={props.onClose}
title="CreateJmxCredentialModal"
>
Jmx Auth Form
</Modal>
);
}),
};
});

jest.mock('@app/Shared/Services/NotificationChannel.service', () => {
const mockNotification = { message: { target: 'service:jmx:rmi://someUrl' } } as NotificationMessage;
return {
...jest.requireActual('@app/Shared/Services/NotificationChannel.service'),
NotificationChannel: jest.fn(() => {
return {
messages: jest
.fn()
.mockReturnValueOnce(of()) // 'renders correctly'
.mockReturnValueOnce(of())
.mockReturnValueOnce(of())

.mockReturnValueOnce(of()) // 'adds the correct table entry when a stored notification is received'
.mockReturnValueOnce(of())
.mockReturnValueOnce(of(mockNotification))

.mockReturnValueOnce(of()) // 'removes the correct table entry when a deletion notification is received'
.mockReturnValueOnce(of(mockNotification))
.mockReturnValueOnce(of())

.mockReturnValueOnce(of()) // 'renders an empty table after receiving deletion notifications for all credentials'
.mockReturnValueOnce(of(mockNotification))
.mockReturnValueOnce(of())

.mockReturnValue(of()), // all other tests
};
}),
};
});

jest.mock('@app/Shared/Services/Target.service', () => {
return {
...jest.requireActual('@app/Shared/Services/Target.service'),
TargetService: jest.fn(() => {
return {
deleteCredentials: jest.fn(),
};
}),
};
});

jest.mock('@app/Shared/Services/Api.service', () => {
return {
ApiService: jest.fn(() => {
return {
getTargetsWithStoredJmxCredentials: jest
.fn()
.mockReturnValueOnce(of([mockTarget]))
.mockReturnValueOnce(of([]))
.mockReturnValueOnce(of([mockTarget, mockAnotherTarget]))
.mockReturnValueOnce(of([mockTarget]))
.mockReturnValueOnce(of([]))
.mockReturnValueOnce(of([]))
.mockReturnValueOnce(of([mockTarget, mockAnotherTarget]))
.mockReturnValueOnce(of([mockTarget, mockAnotherTarget])),
deleteTargetCredentials: jest.fn(() => {
return of(true);
}),
};
}),
};
});

jest.mock('@app/Shared/Services/Targets.service', () => {
return {
TargetsService: jest.fn(() => {
return {
targets: jest.fn(() => {
return of([mockTarget, mockAnotherTarget]);
}),
};
}),
};
});

import { StoreJmxCredentials } from '@app/SecurityPanel/StoreJmxCredentials';
import { ServiceContext, defaultServices } from '@app/Shared/Services/Services';

describe('<StoreJmxCredentials />', () => {
it('renders correctly', async () => {
let tree;
await act(async () => {
tree = renderer.create(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);
});
expect(tree.toJSON()).toMatchSnapshot();
});

it('adds the correct table entry when a stored notification is received', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.getByText('fooTarget')).toBeInTheDocument();
});

it('removes the correct table entry when a deletion notification is received', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.queryByText('fooTarget')).not.toBeInTheDocument();
expect(screen.getByText('anotherTarget')).toBeInTheDocument();
});

it('renders an empty table after receiving deletion notifications for all credentials', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.queryByText('fooTarget')).not.toBeInTheDocument();
expect(screen.getByText('No Stored Credentials')).toBeInTheDocument();
});

it('displays empty state text when the table is empty', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.getByText('No Stored Credentials')).toBeInTheDocument();
});

it('opens the JMX auth modal when Add is clicked', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);
userEvent.click(screen.getByText('Add'));
expect(screen.getByText('CreateJmxCredentialModal')).toBeInTheDocument();

userEvent.click(screen.getByLabelText('Close'));
expect(screen.queryByText('CreateJmxCredentialModal')).not.toBeInTheDocument();
});

it('makes a delete request when deleting one credential', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.getByText('fooTarget')).toBeInTheDocument();
expect(screen.getByText('anotherTarget')).toBeInTheDocument();

userEvent.click(screen.getByLabelText('credentials-table-row-0-check'));
userEvent.click(screen.getByText('Delete'));

const deleteRequestSpy = jest.spyOn(defaultServices.api, 'deleteTargetCredentials');

expect(deleteRequestSpy).toHaveBeenCalledTimes(1);
expect(deleteRequestSpy).toHaveBeenCalledWith(mockTarget);
});

it('makes multiple delete requests when all credentials are deleted at once', () => {
render(
<ServiceContext.Provider value={defaultServices}>
<StoreJmxCredentials />
</ServiceContext.Provider>
);

expect(screen.getByText('anotherTarget')).toBeInTheDocument();
expect(screen.getByText('fooTarget')).toBeInTheDocument();

const checkboxes = screen.getAllByRole('checkbox');
const selectAllCheck = checkboxes[0];
userEvent.click(selectAllCheck);
userEvent.click(screen.getByText('Delete'));

const deleteRequestSpy = jest.spyOn(defaultServices.api, 'deleteTargetCredentials');

expect(deleteRequestSpy).toHaveBeenCalledTimes(2);
expect(deleteRequestSpy).nthCalledWith(1, mockTarget);
expect(deleteRequestSpy).nthCalledWith(2, mockAnotherTarget);
});
});
Loading