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

Add tests for the NewExperiment page #109

Merged
merged 4 commits into from
Nov 7, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
2 changes: 1 addition & 1 deletion frontend/mock-backend/mock-api-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export default (app: express.Application) => {

app.post(v1beta1Prefix + '/experiments', (req, res) => {
const experiment: ApiExperiment = req.body;
if (fixedData.experiments.find(e => e.name.toLowerCase() === experiment.name.toLowerCase())) {
if (fixedData.experiments.find(e => e.name!.toLowerCase() === experiment.name!.toLowerCase())) {
res.status(404).send('An experiment with teh same name already exists');
return;
}
Expand Down
235 changes: 235 additions & 0 deletions frontend/src/pages/NewExperiment.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,235 @@
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import * as React from 'react';
import NewExperiment from './NewExperiment';
import TestUtils from '../TestUtils';
import { shallow } from 'enzyme';
import { PageProps } from './Page';
import { Apis } from '../lib/Apis';
import { RoutePage } from '../components/Router';

describe('NewExperiment', () => {
const createExperimentSpy = jest.spyOn(Apis.experimentServiceApi, 'createExperiment');
const historyPushSpy = jest.fn();
const updateDialogSpy = jest.fn();
const updateSnackbarSpy = jest.fn();
const updateToolbarSpy = jest.fn();

function generateProps(): PageProps {
return {
history: { push: historyPushSpy } as any,
location: { pathname: RoutePage.NEW_EXPERIMENT } as any,
match: '' as any,
toolbarProps: NewExperiment.prototype.getInitialToolbarState(),
updateBanner: () => null,
updateDialog: updateDialogSpy,
updateSnackbar: updateSnackbarSpy,
updateToolbar: updateToolbarSpy,
};
}

beforeEach(() => {
// Reset mocks
createExperimentSpy.mockReset();
historyPushSpy.mockReset();
updateDialogSpy.mockReset();
updateSnackbarSpy.mockReset();
updateToolbarSpy.mockReset();

createExperimentSpy.mockImplementation(() => ({ id: 'new-experiment-id' }));
});

it('renders the new experiment page', () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);

expect(tree).toMatchSnapshot();
tree.unmount();
});

it('does not include any action buttons in the toolbar', () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);

expect(updateToolbarSpy).toHaveBeenCalledWith({
actions: [],
breadcrumbs: [
{ displayName: 'Experiments', href: '/experiments'},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use RoutePage.EXPERIMENTS instead of hard coding the path here? Same on the next line.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. I started doing this in NewRun but forgot to update it here.

{ displayName: 'New experiment', href: '/experiments/new'}
],
});
tree.unmount();
});

it('Enables the \'Next\' button when an experiment name is entered', () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);
(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment name' } });

expect(tree).toMatchSnapshot();
tree.unmount();
});

rileyjbauer marked this conversation as resolved.
Show resolved Hide resolved
it('Updates the experiment name', () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);
(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment name' } });

expect(tree.state()).toEqual({
description: '',
experimentName: 'experiment name',
isbeingCreated: false,
validationError: '',
});
tree.unmount();
});

it('Updates the experiment description', () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);
(tree.instance() as any).handleChange('description')({ target: { value: 'a description!' } });

expect(tree.state()).toEqual({
description: 'a description!',
experimentName: '',
isbeingCreated: false,
validationError: 'Experiment name is required',
});
tree.unmount();
});

it('sets the page to a busy state upon clicking \'Next\'', async () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(tree.state()).toHaveProperty('isbeingCreated', true);
rileyjbauer marked this conversation as resolved.
Show resolved Hide resolved
tree.unmount();
});

it('calls the createExperiment API with the new experiment upon clicking \'Next\'', async () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment name' } });
(tree.instance() as any).handleChange('description')({ target: { value: 'experiment description' } });

tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(createExperimentSpy).toHaveBeenCalledWith({
description: 'experiment description',
name: 'experiment name',
});
tree.unmount();
});

it('navigates to NewRun page upon successful creation', async () => {
const experimentId = 'test-exp-id-1';
createExperimentSpy.mockImplementation(() => ({ id: experimentId }));
const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(historyPushSpy).toHaveBeenCalledWith(
RoutePage.NEW_RUN
+ `?experimentId=${experimentId}`
+ `&firstRunInExperiment=1`);
tree.unmount();
});

it('includes pipeline ID in NewRun page query params if present', async () => {
const experimentId = 'test-exp-id-1';
createExperimentSpy.mockImplementation(() => ({ id: experimentId }));

const pipelineId = 'pipelineId=some-pipeline-id';
const props = generateProps();
props.location.search = `?pipelineId=${pipelineId}`;
const tree = shallow(<NewExperiment {...props as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(historyPushSpy).toHaveBeenCalledWith(
RoutePage.NEW_RUN
+ `?experimentId=${experimentId}`
+ `&pipelineId=${pipelineId}`
+ `&firstRunInExperiment=1`);
tree.unmount();
});

it('shows snackbar confirmation after experiment is created', async () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(updateSnackbarSpy).toHaveBeenLastCalledWith({
autoHideDuration: 10000,
message: 'Successfully created new Experiment: experiment-name',
open: true,
});
tree.unmount();
});

it('unsets busy state when creation fails', async () => {
// tslint:disable-next-line:no-console
console.error = jest.spyOn(console, 'error').mockImplementation();

const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

TestUtils.makeErrorResponseOnce(createExperimentSpy, 'test error!');
tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(tree.state()).toHaveProperty('isbeingCreated', false);
tree.unmount();
});

it('shows error dialog when creation fails', async () => {
// tslint:disable-next-line:no-console
console.error = jest.spyOn(console, 'error').mockImplementation();

const tree = shallow(<NewExperiment {...generateProps() as any} />);

(tree.instance() as any).handleChange('experimentName')({ target: { value: 'experiment-name' } });

TestUtils.makeErrorResponseOnce(createExperimentSpy, 'test error!');
tree.find('#createExperimentBtn').simulate('click');
await TestUtils.flushPromises();

const call = updateDialogSpy.mock.calls[0][0];
expect(call).toHaveProperty('title', 'Experiment creation failed');
expect(call).toHaveProperty('content', 'test error!');
tree.unmount();
});

it('navigates to experiment list page upon cancellation', async () => {
const tree = shallow(<NewExperiment {...generateProps() as any} />);
tree.find('#cancelNewExperimentBtn').simulate('click');
await TestUtils.flushPromises();

expect(historyPushSpy).toHaveBeenCalledWith(RoutePage.EXPERIMENTS);
tree.unmount();
});
});
4 changes: 3 additions & 1 deletion frontend/src/pages/NewExperiment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ class NewExperiment extends Page<{}, NewExperimentState> {
<BusyButton id='createExperimentBtn' disabled={!!validationError} busy={this.state.isbeingCreated}
className={commonCss.buttonAction} title={'Next'}
onClick={this._create.bind(this)} />
<Button onClick={() => this.props.history.push(RoutePage.EXPERIMENTS)}>Cancel</Button>
<Button id='cancelNewExperimentBtn' onClick={() => this.props.history.push(RoutePage.EXPERIMENTS)}>
Cancel
</Button>
<div className={css.errorMessage}>{validationError}</div>
</div>
</div>
Expand Down
Loading