Context test tools (#168)

* add enzyme test helper with lingui provider

* add router context to enzyme test helper

* get 18n, router, & config contexts rendering together in enzyme helper

* add config context to enzyme helpers

* add network and dialog contexts to enzymeHelpers

* convert OrganizationForm tests to use new mountWithContexts helper

* default all context value keys to default unless provided

* document use of mountWithContexts()

* fix typo in CONTRIBUTING.md

* update Organizations to use mountWithContext
This commit is contained in:
Keith Grant
2019-04-18 10:03:06 -04:00
committed by GitHub
parent 7c2554be8c
commit ae72d8dce5
11 changed files with 834 additions and 296 deletions

View File

@@ -0,0 +1,78 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`mountWithContexts injected ConfigProvider should mount and render with custom Config value 1`] = `
<Foo>
<Config>
<div>
Fizz
1.1
</div>
</Config>
</Foo>
`;
exports[`mountWithContexts injected ConfigProvider should mount and render with default values 1`] = `
<Foo>
<Config>
<div />
</Config>
</Foo>
`;
exports[`mountWithContexts injected I18nProvider should mount and render 1`] = `
<div>
<I18n
update={true}
withHash={true}
>
<span>
Text content
</span>
</I18n>
</div>
`;
exports[`mountWithContexts injected I18nProvider should mount and render deeply nested consumer 1`] = `
<Parent>
<Child>
<I18n
update={true}
withHash={true}
>
<div>
Text content
</div>
</I18n>
</Child>
</Parent>
`;
exports[`mountWithContexts injected Network should mount and render 1`] = `
<Foo
api={
Object {
"getConfig": [Function],
}
}
handleHttpError={[Function]}
>
<div>
test
</div>
</Foo>
`;
exports[`mountWithContexts injected Router should mount and render 1`] = `
<div>
<Link
replace={false}
to="/"
>
<a
onClick={[Function]}
>
home
</a>
</Link>
</div>
`;

151
__tests__/enzymeHelpers.jsx Normal file
View File

@@ -0,0 +1,151 @@
/*
* Enzyme helpers for injecting top-level contexts
* derived from https://lingui.js.org/guides/testing.html
*/
import React from 'react';
import { shape, object, string, arrayOf, func } from 'prop-types';
import { mount, shallow } from 'enzyme';
import { I18nProvider } from '@lingui/react';
import { ConfigProvider } from '../src/contexts/Config';
import { _NetworkProvider } from '../src/contexts/Network';
import { RootDialogProvider } from '../src/contexts/RootDialog';
const language = 'en-US';
const intlProvider = new I18nProvider(
{
language,
catalogs: {
[language]: {}
}
},
{}
);
const {
linguiPublisher: { i18n: originalI18n }
} = intlProvider.getChildContext();
const defaultContexts = {
linguiPublisher: {
i18n: {
...originalI18n,
_: key => key.id, // provide _ macro, for just passing down the key
toJSON: () => '/i18n/',
},
},
config: {
ansible_version: null,
custom_virtualenvs: [],
version: null,
custom_logo: null,
custom_login_info: null,
toJSON: () => '/config/'
},
router: {
history: {
push: () => {},
replace: () => {},
createHref: () => {},
},
route: {
location: {
hash: '',
pathname: '',
search: '',
state: '',
},
match: {
params: {},
isExact: false,
path: '',
url: '',
},
},
toJSON: () => '/router/',
},
network: {
api: {
getConfig: () => {},
},
handleHttpError: () => {},
},
dialog: {}
};
const providers = {
config: ConfigProvider,
network: _NetworkProvider,
dialog: RootDialogProvider,
};
function wrapContexts (node, context) {
let wrapped = node;
let isFirst = true;
Object.keys(providers).forEach(key => {
if (context[key]) {
const Provider = providers[key];
wrapped = (
<Provider
value={context[key]}
i18n={isFirst ? defaultContexts.linguiPublisher.i18n : null}
>
{wrapped}
</Provider>
);
isFirst = false;
}
});
return wrapped;
}
function applyDefaultContexts (context) {
if (!context) {
return defaultContexts;
}
const newContext = {};
Object.keys(defaultContexts).forEach(key => {
newContext[key] = {
...defaultContexts[key],
...context[key],
};
});
return newContext;
}
export function shallowWithContexts (node, options = {}) {
const context = applyDefaultContexts(options.context);
return shallow(wrapContexts(node, context));
}
export function mountWithContexts (node, options = {}) {
const context = applyDefaultContexts(options.context);
const childContextTypes = {
linguiPublisher: shape({
i18n: object.isRequired
}).isRequired,
config: shape({
ansible_version: string,
custom_virtualenvs: arrayOf(string),
version: string,
custom_logo: string,
custom_login_info: string,
}),
router: shape({
route: shape({
location: shape({}),
match: shape({}),
}).isRequired,
history: shape({}).isRequired,
}),
network: shape({
api: shape({}).isRequired,
handleHttpError: func.isRequired,
}),
dialog: shape({
title: string,
setRootDialogMessage: func,
clearRootDialogMessage: func,
}),
...options.childContextTypes
};
return mount(wrapContexts(node, context), { context, childContextTypes });
}

View File

@@ -0,0 +1,194 @@
import React from 'react';
import { Link } from 'react-router-dom';
// import { mount } from 'enzyme';
import { I18n } from '@lingui/react';
import { t } from '@lingui/macro';
import { mountWithContexts } from './enzymeHelpers';
import { Config } from '../src/contexts/Config';
import { withNetwork } from '../src/contexts/Network';
import { withRootDialog } from '../src/contexts/RootDialog';
describe('mountWithContexts', () => {
describe('injected I18nProvider', () => {
test('should mount and render', () => {
const wrapper = mountWithContexts(
<div>
<I18n>
{({ i18n }) => (
<span>{i18n._(t`Text content`)}</span>
)}
</I18n>
</div>
);
expect(wrapper.find('div')).toMatchSnapshot();
});
test('should mount and render deeply nested consumer', () => {
const Child = () => (
<I18n>
{({ i18n }) => (
<div>{i18n._(t`Text content`)}</div>
)}
</I18n>
);
const Parent = () => (<Child />);
const wrapper = mountWithContexts(<Parent />);
expect(wrapper.find('Parent')).toMatchSnapshot();
});
});
describe('injected Router', () => {
it('should mount and render', () => {
const wrapper = mountWithContexts(
<div>
<Link to="/">home</Link>
</div>
);
expect(wrapper.find('div')).toMatchSnapshot();
});
it('should mount and render with stubbed context', () => {
const context = {
router: {
history: {
push: jest.fn(),
replace: jest.fn(),
createHref: jest.fn(),
},
route: {
location: {},
match: {}
}
}
};
const wrapper = mountWithContexts(
(
<div>
<Link to="/">home</Link>
</div>
),
{ context }
);
const link = wrapper.find('Link');
expect(link).toHaveLength(1);
link.simulate('click', { button: 0 });
wrapper.update();
expect(context.router.history.push).toHaveBeenCalledWith('/');
});
});
describe('injected ConfigProvider', () => {
it('should mount and render with default values', () => {
const Foo = () => (
<Config>
{value => (
<div>
{value.custom_virtualenvs[0]}
{value.version}
</div>
)}
</Config>
);
const wrapper = mountWithContexts(<Foo />);
expect(wrapper.find('Foo')).toMatchSnapshot();
});
it('should mount and render with custom Config value', () => {
const config = {
custom_virtualenvs: ['Fizz', 'Buzz'],
version: '1.1',
};
const Foo = () => (
<Config>
{value => (
<div>
{value.custom_virtualenvs[0]}
{value.version}
</div>
)}
</Config>
);
const wrapper = mountWithContexts(
<Foo />,
{ context: { config } }
);
expect(wrapper.find('Foo')).toMatchSnapshot();
});
});
describe('injected Network', () => {
it('should mount and render', () => {
const Foo = () => (
<div>test</div>
);
const Bar = withNetwork(Foo);
const wrapper = mountWithContexts(<Bar />);
expect(wrapper.find('Foo')).toMatchSnapshot();
});
it('should mount and render with stubbed api', () => {
const network = {
api: {
getFoo: jest.fn().mockReturnValue('foo value'),
},
};
const Foo = ({ api }) => (
<div>{api.getFoo()}</div>
);
const Bar = withNetwork(Foo);
const wrapper = mountWithContexts(<Bar />, { context: { network } });
expect(network.api.getFoo).toHaveBeenCalledTimes(1);
expect(wrapper.find('div').text()).toEqual('foo value');
});
});
describe('injected root dialog', () => {
it('should mount and render', () => {
const Foo = ({ title, setRootDialogMessage }) => (
<div>
<span>{title}</span>
<button
type="button"
onClick={() => setRootDialogMessage({ title: 'error' })}
>
click
</button>
</div>
);
const Bar = withRootDialog(Foo);
const wrapper = mountWithContexts(<Bar />);
expect(wrapper.find('span').text()).toEqual('');
wrapper.find('button').simulate('click');
wrapper.update();
expect(wrapper.find('span').text()).toEqual('error');
});
it('should mount and render with stubbed value', () => {
const dialog = {
title: 'this be the title',
setRootDialogMessage: jest.fn(),
};
const Foo = ({ title, setRootDialogMessage }) => (
<div>
<span>{title}</span>
<button
type="button"
onClick={() => setRootDialogMessage('error')}
>
click
</button>
</div>
);
const Bar = withRootDialog(Foo);
const wrapper = mountWithContexts(<Bar />, { context: { dialog } });
expect(wrapper.find('span').text()).toEqual('this be the title');
wrapper.find('button').simulate('click');
expect(dialog.setRootDialogMessage).toHaveBeenCalledWith('error');
});
});
});

View File

@@ -1,20 +1,14 @@
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { mount } from 'enzyme';
import { I18nProvider } from '@lingui/react';
import { mountWithContexts } from '../../enzymeHelpers';
import Organizations from '../../../src/pages/Organizations/Organizations';
describe('<Organizations />', () => {
test('initially renders succesfully', () => {
mount(
<MemoryRouter initialEntries={['/organizations']} initialIndex={0}>
<I18nProvider>
<Organizations
match={{ path: '/organizations', url: '/organizations' }}
location={{ search: '', pathname: '/organizations' }}
/>
</I18nProvider>
</MemoryRouter>
mountWithContexts(
<Organizations
match={{ path: '/organizations', url: '/organizations' }}
location={{ search: '', pathname: '/organizations' }}
/>
);
});
});

View File

@@ -1,15 +1,10 @@
import React from 'react';
import { mount } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import { I18nProvider } from '@lingui/react';
import { mountWithContexts } from '../../../enzymeHelpers';
import { sleep } from '../../../testUtils';
import { ConfigProvider } from '../../../../src/contexts/Config';
import { NetworkProvider } from '../../../../src/contexts/Network';
import OrganizationForm, { _OrganizationForm } from '../../../../src/pages/Organizations/components/OrganizationForm';
import OrganizationForm from '../../../../src/pages/Organizations/components/OrganizationForm';
describe('<OrganizationForm />', () => {
let api;
let networkProviderValue;
let network;
const mockData = {
id: 1,
@@ -22,14 +17,11 @@ describe('<OrganizationForm />', () => {
};
beforeEach(() => {
api = {
getInstanceGroups: jest.fn(),
};
network = {};
});
networkProviderValue = {
api,
handleHttpError: () => {}
};
afterEach(() => {
jest.clearAllMocks();
});
test('should request related instance groups from api', () => {
@@ -37,25 +29,24 @@ describe('<OrganizationForm />', () => {
{ name: 'One', id: 1 },
{ name: 'Two', id: 2 }
];
api.getOrganizationInstanceGroups = jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
));
mount(
<MemoryRouter initialEntries={['/organizations/1']} initialIndex={0}>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<_OrganizationForm
api={api}
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
).find('OrganizationForm');
network.api = {
getOrganizationInstanceGroups: jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
))
};
mountWithContexts(
(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
), {
context: { network },
}
);
expect(api.getOrganizationInstanceGroups).toHaveBeenCalledTimes(1);
expect(network.api.getOrganizationInstanceGroups).toHaveBeenCalledTimes(1);
});
test('componentDidMount should set instanceGroups to state', async () => {
@@ -63,42 +54,36 @@ describe('<OrganizationForm />', () => {
{ name: 'One', id: 1 },
{ name: 'Two', id: 2 }
];
api.getOrganizationInstanceGroups = jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
));
const wrapper = mount(
<MemoryRouter initialEntries={['/organizations/1']} initialIndex={0}>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<_OrganizationForm
organization={mockData}
api={api}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
).find('OrganizationForm');
network.api = {
getOrganizationInstanceGroups: jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
))
};
const wrapper = mountWithContexts(
(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
), {
context: { network },
}
);
await wrapper.instance().componentDidMount();
expect(wrapper.state().instanceGroups).toEqual(mockInstanceGroups);
await sleep(0);
expect(network.api.getOrganizationInstanceGroups).toHaveBeenCalled();
expect(wrapper.find('OrganizationForm').state().instanceGroups).toEqual(mockInstanceGroups);
});
test('changing instance group successfully sets instanceGroups state', () => {
const wrapper = mount(
<MemoryRouter>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
).find('OrganizationForm');
const wrapper = mountWithContexts(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
);
const lookup = wrapper.find('InstanceGroupsLookup');
expect(lookup.length).toBe(1);
@@ -109,7 +94,7 @@ describe('<OrganizationForm />', () => {
name: 'foo'
}
], 'instanceGroups');
expect(wrapper.state().instanceGroups).toEqual([
expect(wrapper.find('OrganizationForm').state().instanceGroups).toEqual([
{
id: 1,
name: 'foo'
@@ -118,19 +103,13 @@ describe('<OrganizationForm />', () => {
});
test('changing inputs should update form values', () => {
const wrapper = mount(
<MemoryRouter>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
).find('OrganizationForm');
const wrapper = mountWithContexts(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
);
const form = wrapper.find('Formik');
wrapper.find('input#org-name').simulate('change', {
@@ -147,20 +126,16 @@ describe('<OrganizationForm />', () => {
const config = {
custom_virtualenvs: ['foo', 'bar'],
};
const wrapper = mount(
<MemoryRouter>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<ConfigProvider value={config}>
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
</ConfigProvider>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
const wrapper = mountWithContexts(
(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={jest.fn()}
/>
), {
context: { config },
}
);
expect(wrapper.find('FormSelect')).toHaveLength(1);
expect(wrapper.find('FormSelectOption')).toHaveLength(2);
@@ -168,20 +143,13 @@ describe('<OrganizationForm />', () => {
test('calls handleSubmit when form submitted', async () => {
const handleSubmit = jest.fn();
const wrapper = mount(
<MemoryRouter>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<OrganizationForm
organization={mockData}
api={api}
handleSubmit={handleSubmit}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
).find('OrganizationForm');
const wrapper = mountWithContexts(
<OrganizationForm
organization={mockData}
handleSubmit={handleSubmit}
handleCancel={jest.fn()}
/>
);
expect(handleSubmit).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Save"]').simulate('click');
await sleep(1);
@@ -197,34 +165,33 @@ describe('<OrganizationForm />', () => {
{ name: 'One', id: 1 },
{ name: 'Two', id: 2 }
];
api.getOrganizationInstanceGroups = jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
));
network.api = {
getOrganizationInstanceGroups: jest.fn(() => (
Promise.resolve({ data: { results: mockInstanceGroups } })
))
};
const mockDataForm = {
name: 'Foo',
description: 'Bar',
custom_virtualenv: 'Fizz',
};
const handleSubmit = jest.fn();
api.updateOrganizationDetails = jest.fn().mockResolvedValue(1, mockDataForm);
api.associateInstanceGroup = jest.fn().mockResolvedValue('done');
api.disassociate = jest.fn().mockResolvedValue('done');
const wrapper = mount(
<I18nProvider>
<MemoryRouter initialEntries={['/organizations/1']} initialIndex={0}>
<NetworkProvider value={networkProviderValue}>
<_OrganizationForm
organization={mockData}
api={api}
handleSubmit={handleSubmit}
handleCancel={jest.fn()}
/>
</NetworkProvider>
</MemoryRouter>
</I18nProvider>
).find('OrganizationForm');
network.api.updateOrganizationDetails = jest.fn().mockResolvedValue(1, mockDataForm);
network.api.associateInstanceGroup = jest.fn().mockResolvedValue('done');
network.api.disassociate = jest.fn().mockResolvedValue('done');
const wrapper = mountWithContexts(
(
<OrganizationForm
organization={mockData}
handleSubmit={handleSubmit}
handleCancel={jest.fn()}
/>
), {
context: { network },
}
);
await wrapper.instance().componentDidMount();
await sleep(0);
wrapper.find('InstanceGroupsLookup').prop('onChange')([
{ name: 'One', id: 1 },
@@ -238,18 +205,12 @@ describe('<OrganizationForm />', () => {
test('calls "handleCancel" when Cancel button is clicked', () => {
const handleCancel = jest.fn();
const wrapper = mount(
<MemoryRouter>
<I18nProvider>
<NetworkProvider value={networkProviderValue}>
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={handleCancel}
/>
</NetworkProvider>
</I18nProvider>
</MemoryRouter>
const wrapper = mountWithContexts(
<OrganizationForm
organization={mockData}
handleSubmit={jest.fn()}
handleCancel={handleCancel}
/>
);
expect(handleCancel).not.toHaveBeenCalled();
wrapper.find('button[aria-label="Cancel"]').prop('onClick')();