Initial commit

This commit is contained in:
Jon Ervine
2021-03-02 20:53:43 +08:00
parent 89d3a2dfe1
commit f961b728fa
2919 changed files with 388582 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
{
"rules": {
"react/jsx-pascal-case": 0
}
}
@@ -0,0 +1,63 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`mountWithContexts injected ConfigProvider should mount and render with custom Config value 1`] = `
<Foo>
<div>
Fizz
1.1
</div>
</Foo>
`;
exports[`mountWithContexts injected ConfigProvider should mount and render with default values 1`] = `
<Foo>
<div />
</Foo>
`;
exports[`mountWithContexts injected I18nProvider should mount and render 1`] = `
<div>
<span>
Text content
</span>
</div>
`;
exports[`mountWithContexts injected I18nProvider should mount and render deeply nested consumer 1`] = `
<Parent>
<WithI18n>
<I18n
update={true}
withHash={true}
>
<Component
i18n={"/i18n/"}
>
<div>
Text content
</div>
</Component>
</I18n>
</WithI18n>
</Parent>
`;
exports[`mountWithContexts injected Router should mount and render 1`] = `
<div>
<Link
to="/"
>
<LinkAnchor
href="/"
navigate={[Function]}
>
<a
href="/"
onClick={[Function]}
>
home
</a>
</LinkAnchor>
</Link>
</div>
`;
+47
View File
@@ -0,0 +1,47 @@
// eslint-disable-next-line import/prefer-default-export
export function describeNotificationMixin (Model, name) {
describe(name, () => {
const mockHttp = ({ post: jest.fn(() => Promise.resolve()) });
const ModelAPI = new Model(mockHttp);
afterEach(() => {
jest.clearAllMocks();
});
const parameters = ['success', 'error'];
parameters.forEach((type) => {
const label = `[notificationType=${type}, associationState=true`;
const testName = `associateNotificationTemplate ${label} makes expected http calls`;
test(testName, async (done) => {
await ModelAPI.associateNotificationTemplate(1, 21, type);
const expectedPath = `${ModelAPI.baseUrl}1/notification_templates_${type}/`;
expect(mockHttp.post).toHaveBeenCalledTimes(1);
const expectedParams = { id: 21 };
expect(mockHttp.post.mock.calls.pop()).toEqual([expectedPath, expectedParams]);
done();
});
});
parameters.forEach((type) => {
const label = `[notificationType=${type}, associationState=false`;
const testName = `disassociateNotificationTemplate ${label} makes expected http calls`;
test(testName, async (done) => {
await ModelAPI.disassociateNotificationTemplate(1, 21, type);
const expectedPath = `${ModelAPI.baseUrl}1/notification_templates_${type}/`;
expect(mockHttp.post).toHaveBeenCalledTimes(1);
const expectedParams = { id: 21, disassociate: true };
expect(mockHttp.post.mock.calls.pop()).toEqual([expectedPath, expectedParams]);
done();
});
});
});
}
+175
View File
@@ -0,0 +1,175 @@
/*
* 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 } from 'prop-types';
import { mount, shallow } from 'enzyme';
import { MemoryRouter, Router } from 'react-router-dom';
import { I18nProvider } from '@lingui/react';
import { ConfigProvider } from '../src/contexts/Config';
const language = 'en-US';
const intlProvider = new I18nProvider(
{
language,
catalogs: {
[language]: {},
},
},
{}
);
const {
linguiPublisher: { i18n: originalI18n },
} = intlProvider.getChildContext();
const defaultContexts = {
linguiPublisher: {
i18n: {
...originalI18n,
_: key => {
if (key.values) {
Object.entries(key.values).forEach(([k, v]) => {
key.id = key.id.replace(new RegExp(`\\{${k}\\}`), v);
});
}
return key.id;
}, // provide _ macro, for just passing down the key
toJSON: () => '/i18n/',
},
},
config: {
ansible_version: null,
custom_virtualenvs: [],
version: null,
me: { is_superuser: true },
toJSON: () => '/config/',
},
router: {
history_: {
push: () => {},
replace: () => {},
createHref: () => {},
listen: () => {},
location: {
hash: '',
pathname: '',
search: '',
state: '',
},
toJSON: () => '/history/',
},
route: {
location: {
hash: '',
pathname: '',
search: '',
state: '',
},
match: {
params: {},
isExact: false,
path: '',
url: '',
},
},
toJSON: () => '/router/',
},
};
function wrapContexts(node, context) {
const { config, router } = context;
class Wrap extends React.Component {
render() {
// eslint-disable-next-line react/no-this-in-sfc
const { children, ...props } = this.props;
const component = React.cloneElement(children, props);
if (router.history) {
return (
<ConfigProvider value={config}>
<Router history={router.history}>{component}</Router>
</ConfigProvider>
);
}
return (
<ConfigProvider value={config}>
<MemoryRouter>{component}</MemoryRouter>
</ConfigProvider>
);
}
}
return <Wrap>{node}</Wrap>;
}
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, // eslint-disable-line react/forbid-prop-types
}).isRequired,
config: shape({
ansible_version: string,
custom_virtualenvs: arrayOf(string),
version: string,
}),
router: shape({
route: shape({
location: shape({}),
match: shape({}),
}).isRequired,
history: shape({}),
}),
...options.childContextTypes,
};
return mount(wrapContexts(node, context), { context, childContextTypes });
}
/**
* Wait for element(s) to achieve a desired state.
*
* @param[wrapper] - A ReactWrapper instance
* @param[selector] - The selector of the element(s) to wait for.
* @param[callback] - Callback to poll - by default this checks for a node count of 1.
*/
export function waitForElement(
wrapper,
selector,
callback = el => el.length === 1
) {
const interval = 100;
return new Promise((resolve, reject) => {
let attempts = 30;
(function pollElement() {
wrapper.update();
const el = wrapper.find(selector);
if (callback(el)) {
return resolve(el);
}
if (--attempts <= 0) {
const message = `Expected condition for <${selector}> not met: ${callback.toString()}`;
return reject(new Error(message));
}
return setTimeout(pollElement, interval);
})();
});
}
@@ -0,0 +1,153 @@
import React, { Component } from 'react';
import { createMemoryHistory } from 'history';
import { Link } from 'react-router-dom';
import { mountWithContexts, waitForElement } from './enzymeHelpers';
import { Config } from '../src/contexts/Config';
describe('mountWithContexts', () => {
describe('injected I18nProvider', () => {
test('should mount and render', () => {
const Child = () => (
<div>
<span>Text content</span>
</div>
);
const wrapper = mountWithContexts(<Child />);
expect(wrapper.find('div')).toMatchSnapshot();
});
test('should mount and render deeply nested consumer', () => {
const Child = () => <div>Text content</div>;
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: createMemoryHistory({}),
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.location.pathname).toEqual('/');
});
});
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();
});
});
});
/**
* This is a fixture for testing async components. It renders a div
* after a short amount of time.
*/
class TestAsyncComponent extends Component {
constructor(props) {
super(props);
this.state = { displayElement: false };
}
componentDidMount() {
setTimeout(() => this.setState({ displayElement: true }), 500);
}
render() {
const { displayElement } = this.state;
if (displayElement) {
return <div id="test-async-component" />;
}
return null;
}
}
describe('waitForElement', () => {
it('waits for the element and returns it', async done => {
const selector = '#test-async-component';
const wrapper = mountWithContexts(<TestAsyncComponent />);
expect(wrapper.exists(selector)).toEqual(false);
const elem = await waitForElement(wrapper, selector);
expect(elem.props().id).toEqual('test-async-component');
expect(wrapper.exists(selector)).toEqual(true);
done();
});
it("eventually throws an error for elements that don't exist", async done => {
const wrapper = mountWithContexts(<div />);
let error;
try {
await waitForElement(wrapper, '#does-not-exist');
} catch (err) {
error = err;
} finally {
expect(error.message).toContain(
'Expected condition for <#does-not-exist> not met'
);
expect(error.message).toContain('el.length === 1');
done();
}
});
});
+4
View File
@@ -0,0 +1,4 @@
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
/* eslint-disable-next-line import/prefer-default-export */
export { sleep };