Skip to content

Instantly share code, notes, and snippets.

@vidaaudrey
Created March 13, 2017 19:00
Show Gist options
  • Save vidaaudrey/68f6af960368644ce363bf811a4e872f to your computer and use it in GitHub Desktop.
Save vidaaudrey/68f6af960368644ce363bf811a4e872f to your computer and use it in GitHub Desktop.
atom snippet
# Your snippets
#
# Atom snippets allow you to enter a simple prefix in the editor and hit tab to
# expand the prefix into a larger code block with templated values.
#
# You can create a new snippet in this file by typing "snip" and then hitting
# tab.
#
# An example CoffeeScript snippet to expand log to console.log:
#
# '.source.coffee':
# 'Console log':
# 'prefix': 'log'
# 'body': 'console.log $1'
#
# Each scope (e.g. '.source.coffee' above) can only be declared once.
#
# This file uses CoffeeScript Object Notation (CSON).
# If you are unfamiliar with CSON, you can read more about it in the
# Atom Flight Manual:
# https://atom.io/docs/latest/using-atom-basic-customization#cson
# 'SnippetName':
# 'prefix': 'SnippetName'
# 'body': """
# Hello Wolrd
# """
'.source.js, .source.jsx, .source.styl, .source.css':
'lorem-pixel':
'prefix': 'lorem-pixel'
'body': """
http://lorempixel.com/${1:400}/${2:200}/${3:city/}
"""
'border1':
'prefix': 'border1'
'body': """
border 1px solid red
"""
'placeholderit':
'prefix': 'placeholderit'
'body': """
http://placehold.it/${1:600x400}/A66506/FFFFFF
"""
'redevice':
'prefix': 'redevice'
'body': """
@require 'bundles/styleguide/learnerApp/deviceDimensionVariables'
"""
'revariables':
'prefix': 'revariables'
'body': """
@require 'bundles/styleguide/learnerApp/variables'
"""
'placeholderit-img':
'prefix': 'placeholderit-img'
'body': """
<img src="//placehold.it/${1:600x400}/A66506/FFFFFF" alt="${2:CourseraAlt}" />
"""
'placeholderit-avatar':
'prefix': 'placeholderit-avatar'
'body': """
<img src="https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg" alt="${2:CourseraAlt}" />
"""
'lorem-pixel-img':
'prefix': 'lorem-pixel-img'
'body': """
<img src="http://lorempixel.com/${1:400}/${2:200}/${3:city/}" alt="${4:CourseraAlt}" />
"""
".source.html, .source.jsx, .source.js":
"fa-inc":
"prefix":"fa-inc"
"body":"<link href='//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css' rel='stylesheet'>"
'fa-star':
'prefix': 'fa-star'
'body': """
<i className='fa fa-${1:star}'></i>
"""
########################## so-styles
'.source.styl':
'recss-simple-story':
'prefix': 'recss-simple-story'
'body': """
@require '../../../__styles__/variables'
.rc-${1:StyleColors}
text-align center
"""
'tem-css':
'prefix': 'tem-css'
'body': """
@require 'bundles/styleguide/learnerApp/deviceDimensionVariables'
@require 'bundles/styleguide/learnerApp/variables'
.rc-${1:CourseCard}
h1
font-size 20px
@media $phone-or-smaller
.rc-${1:CourseCard}
.h1
text-align center
"""
'recss-variable-devide':
'prefix': 'recss-variable-devide'
'body': """
@require 'bundles/styleguide/learnerApp/deviceDimensionVariables'
@require 'bundles/styleguide/learnerApp/variables'
"""
# '.source.styl, .source.js, .source.jsx':
# 'bg':
# 'prefix': 'SnippetName'
# 'body': """
# Hello Wolrd
# """
########################## so-jsx
'.source.js, .source.jsx':
'clo':
'prefix': 'clo'
'body': """
console.warn('---', ${1});
"""
'clo1':
'prefix': 'clo1'
'body': """
console.log('-- ${1:Component} --', this.props, this.state);
"""
'clo-state':
'prefix': 'clo-state'
'body': """
console.warn('---', this.state);
"""
'clo-props':
'prefix': 'clo-props'
'body': """
console.warn('---', this.props);
"""
'es-propTypes':
'prefix': 'es-propTypes'
'body': """
// eslint-disable-line react/forbid-prop-types
"""
'es-propTypes-block':
'prefix': 'es-propTypes-block'
'body': """
/* eslint-disable react/forbid-prop-types */
"""
'es-propTypes-no-unused':
'prefix': 'es-propTypes-no-unused'
'body': """
// eslint-disable-line react/no-unused-prop-types
"""
'es-maxlen':
'prefix': 'es-maxlen'
'body': """
// eslint-disable-line max-len
"""
'es-param-reassign':
'prefix': 'es-param-reassign'
'body': """
// eslint-disable-line no-param-reassign
"""
're-pure':
'prefix': 're-pure'
'body': """
import {pure} from 'recompose';
"""
're-button':
'prefix': 're-button'
'body': """
import Button from 'bundles/coursera-ui/components/basic/Button';
"""
're-TrackedButton':
'prefix': 're-TrackedButton'
'body': """
import withSingleTracked from 'bundles/common/components/withSingleTracked';
import Button from 'bundles/coursera-ui/components/basic/Button';
const TrackedButton = withSingleTracked({type: 'BUTTON'})(Button);
<TrackedButton
type="primary"
onClick={this.toggleFlip}
htmlAttributes={{'data-courselenium': "how-it-works-button"}}
label={_t('How It Works')}
trackingName="how_it_works_button_front"
trackingData={{courseId}}
/>
"""
'cu-button-link':
'prefix': 'cu-button-link'
'body': """
<Button
type="secondary"
tag="a"
size="sm"
label={_t('Preview')}
style={{marginRight: spacing.md}}
htmlAttributes={{
href: this._programHomeLink,
target: '_blank',
rel: 'noopener noreferrer'
}}
/>
"""
'cu-button':
'prefix': 'cu-button'
'body': """
<Button
type="primary"
size="md"
label={_t('Enroll')}
onClick={onClick}
/>
"""
're-svgButton':
'prefix': 're-svgButton'
'body': """
import SvgButton from 'bundles/coursera-ui/components/basic/SvgButton';
"""
'cu-svgButton':
'prefix': 'cu-svgButton'
'body': """
<SvgButton
label="SvgButton primary"
isThemeDark={isThemeDark}
type="primary"
svgElement={
<SvgInvitations
color={isThemeDark ? color.primary : color.iconThemeDark}
hoverColor={color.white}
isThemeDark={isThemeDark}
/>
}
/>
"""
're-apiButton':
'prefix': 're-apiButton'
'body': """
import ApiButton from 'bundles/coursera-ui/components/basic/ApiButton';
"""
're-apiStatusProp':
'prefix': 're-apiStatusProp'
'body': """
import { apiStatusPropType } from 'bundles/coursera-ui/constants/apiNotificationConstants';
"""
're-apiStatusAndProp':
'prefix': 're-apiStatusAndProp'
'body': """
import {
API_BEFORE_SEND, API_IN_PROGRESS, API_SUCCESS, API_ERROR,
apiStatusPropType,
} from 'bundles/coursera-ui/constants/apiNotificationConstants';
"""
'cu-apiButton':
'prefix': 'cu-apiButton'
'body': """
<ApiButton
{...btnAttributes}
onClick={onClick}
apiStatus={apiStatus}
apiStatusAttributesConfig={{
label: {
API_BEFORE_SEND: _t('Unenroll'),
API_IN_PROGRESS: _t('Unenrolling...'),
API_SUCCESS: _t('Unenrolled'),
API_ERROR: _t('Failed'),
}
}}
/>
"""
'divCss':
'prefix': 'divCss'
'body': """
<div {...css(styles.selectizeContainer)}>
${1:}
</div>
"""
'divCssWithClass':
'prefix': 'divCssWithClass'
'body': """
<div {...cssWithClass('${1:horizontal-box}', styles.selectizeContainer)}>
${2:}
</div>
"""
're-formattedMessage':
'prefix': 're-formattedMessage'
'body': """
import { FormattedMessage } from 'js/lib/coursera.react-intl';
<FormattedMessage
message={_t(`Delete {dataSize}
{dataSize, plural, =1 {person} other {people}}?
`)}
dataSize={dataSize}
/>
"""
're-formattedHTMLMessage':
'prefix': 're-formattedHTMLMessage'
'body': """
import { FormattedHTMLMessage } from 'js/lib/coursera.react-intl';
<FormattedHTMLMessage
message={_t(`
We have not yet launched in your country. Please
<a href="{link}" target="_blank" rel="noopener noreferrer">fill this form</a>
to contact sales.
`)}
link={REQUEST_DEMO_LINK}
/>
"""
're-knobs':
'prefix': 're-knobs'
'body': """
import { withKnobs, text, boolean, number } from '@kadira/storybook-addon-knobs';
"""
're-basic':
'prefix': 're-basic'
'body': """
import React, {PropTypes, Component} from 'react';
import {css, StyleSheet, color, spacing, transition} from 'bundles/coursera-ui/styles/theme';
"""
're-recompose':
'prefix': 're-recompose'
'body': """
import { pure, compose } from 'vendor/cnpm/recompose.v0-20-2/index';
"""
're-basic-recompose':
'prefix': 're-basic-recompose'
'body': """
/* eslint-disable no-use-before-define */
import React, {PropTypes, Component} from 'react';
import {
css, cssWithClass, StyleSheet, color, spacing,
} from 'bundles/coursera-ui/styles/theme';
import { pure, compose } from 'vendor/cnpm/recompose.v0-20-2/index';
"""
're-waitForGraphql':
'prefix': 're-waitForGraphql'
'body': """
import waitForGraphQL from 'js/lib/waitForGraphQL';
"""
're-deferToClientSideRender':
'prefix': 're-deferToClientSideRender'
'body': """
import deferToClientSideRender from 'js/lib/deferToClientSideRender';
"""
're-gql':
'prefix': 're-gql'
'body': """
import gql from 'graphql-tag';
"""
're-withFragment':
'prefix': 're-withFragment'
'body': """
import withFragments from 'bundles/graphql/components/withFragments';
"""
're-user':
'prefix': 're-user'
'body': """
import user from 'js/lib/user';
user.get().id
"""
're-user-full':
'prefix': 're-user-full'
'body': """
import user from 'js/lib/user';
user.get().id
user.get().email_address
user.isAuthenticatedUser()
user.isSuperuser()
"""
're-branching':
'prefix': 're-branching'
'body': """
import { withSSRPlaceholder } from 'bundles/coursera-ui/components/hocs/withBranches';
"""
'reBranching-full':
'prefix': 'reBranching-full'
'body': """
import { withSSRPlaceholder } from 'bundles/coursera-ui/components/hocs/withBranches';
import withIsMounted from 'bundles/coursera-ui/components/hocs/withIsMounted';
const CourseCard = () => <div><h1>Dummy Course Card</h1></div>;
const CourseCardPlaceholder = () => <div><h1>Course Card SSR Placeholder</h1></div>;
const CourseCardWithSSRPlaceholderBranch = _.compose(
withIsMounted,
withSSRPlaceholder(CourseCardPlaceholder),
)(CourseCard);
<CourseCardWithSSRPlaceholderBranch isCSROnly />
"""
'rehoistNonReactStatics':
'prefix': 'rehoistNonReactStatics'
'body': """
import hoistNonReactStatics from 'js/lib/hoistNonReactStatics';
"""
'rehoistStatics':
'prefix': 'rehoistStatics'
'body': """
import { hoistStatics } from 'vendor/cnpm/recompose.v0-20-2/index';
"""
'hoistCompNonReactStatics':
'prefix': 'hoistCompNonReactStatics'
'body': """
hoistNonReactStatics(HOC, Component);
"""
're-withSingleTracked':
'prefix': 're-withSingleTracked'
'body': """
import withSingleTracked from 'bundles/common/components/withSingleTracked';
"""
're-theme-color':
'prefix': 're-theme-color'
'body': """
import { color } from 'bundles/coursera-ui/styles/theme';
"""
're-theme':
'prefix': 're-theme'
'body': """
import {
cssWithClass, StyleSheet, css, color, spacing,
} from 'bundles/coursera-ui/styles/theme';
"""
're-ui':
'prefix': 're-ui'
'body': """
import { Avatar } from 'bundles/coursera-ui/index';
"""
'ieslintdisable':
'prefix': 'ieslintdisable'
'body': """
/* eslint-disable no-param-reassign, no-use-before-define, max-len */
"""
'esno-use-before-define':
'prefix': 'esno-use-before-define'
'body': """
/* eslint-disable no-use-before-define */
"""
'ire-theme':
'prefix': 'ire-theme'
'body': """
import {
cssWithClass, StyleSheet, css, color, spacing, gradient, transition,
} from 'src/styles/theme';
"""
'constructor-r':
'prefix': 'constructor-r'
'body': """
constructor(props, context) {
super(props, context);
this.state = {
};
}
"""
'withStyle-export':
'prefix': 'withStyle-export'
'body': """
module.exports = NoDomainSelected;
const styles = StyleSheet.create({
NoDomainSelected: {
minHeight: 300,
},
});
"""
'withstyle-full':
'prefix': 'withstyle-full'
'body': """
import {
cssWithClass, StyleSheet, css, color, spacing, gradient, transition,
} from 'src/styles/theme';
const NoDomainSelected = ({styles}) => {
return (
<div {...cssWithClass('vertical-box align-items-absolute-center', styles.NoDomainSelected)}>
<h2 className="m-b-3">
Please select at least one domain!
</h2>
</div>
);
};
module.exports = NoDomainSelected;
const styles = StyleSheet.create({
NoDomainSelected: {
minHeight: 300,
},
});
"""
'getStylesFromProp':
'prefix': 'getStylesFromProp'
'body': """
const getStylesFromProp = (props, context) => {
return {
root: {
width: '100vw',
height: '100vh',
}
}
}
"""
'reAPIStatus':
'prefix': 'reAPIStatus'
'body': """
import {
API_BEFORE_SEND, API_IN_PROGRESS, API_SUCCESS, API_ERROR
} from 'bundles/phoenix/components/ApiNotification';
"""
'componentName':
'prefix': 'componentName'
'body': """
const componentName = Component.displayName || Component.name;
"""
'withStyles-export':
'prefix': 'withStyles-export'
'body': """
export default withStyles(({}) => ({
red: {
backgroundColor: 'red'
},
font: {
fontSize: 60,
},
blue: {
backgroundColor: 'blue'
},
hover: {
':hover': {
backgroundColor: 'red'
}
},
small: {
'@media (max-width: 600px)': {
backgroundColor: 'red',
}
}
}))(AppWithApiData);
"""
'withKnowbTem':
'prefix': 'withKnowbTem'
'body': """
import { withKnobs, text, boolean, number } from '@kadira/storybook-addon-knobs';
const stories = storiesOf('Storybook Knobs', module);
stories.addDecorator(withKnobs);
stories.add('with a button', () => (
<button
disabled={boolean('Disabled', false)}
>
{text('Label', 'Hello Button')}
</button>
))
stories.add('as dynamic variables', () => {
const name = text('Name', 'Arunoda Susiripala');
const age = number('Age', 89);
const content = `I am ${name} and I'm ${age} years old.`;
return (<div>{content}</div>);
});
"""
'reButton':
'prefix': 'reButton'
'body': """
import Button from 'bundles/coursera-ui/components/basic/Button';
"""
'tem-Button':
'prefix': 'tem-Button'
'body': """
<Button
htmlAttributes={{
className: 'primary',
}}
apiStatusAttributesConfig={{
btnText: {
API_BEFORE_SEND: _t('Upload'),
API_IN_PROGRESS: _t('Uploading...'),
API_SUCCESS: _t('Uploaded'),
API_ERROR: _t('Upload Failed'),
}
}}
apiStatusHtmlAttributesConfig={{
disabled: {
API_BEFORE_SEND: false,
API_IN_PROGRESS: true,
API_SUCCESS: true,
API_ERROR: true,
},
}}
apiPromise={this._getUploadCSVPromise()}
apiInProgressCallback={this.handleApiInProgress}
apiSuccessCallback={this.handleApiSuccess}
apiErrorCallback={this.handleApiError}
/>
"""
'propTypes-apiManager':
'prefix': 'propTypes-apiManager'
'body': """
static propTypes = {
apiManager: React.PropTypes.object.isRequired,
}
"""
'reWithNaptimeAsProp':
'prefix': 'reWithNaptimeAsProp'
'body': """
import withNaptimeAsProp from 'bundles/admin-dashboard-programs/components/members/withNaptimeAsProp';
"""
'reWithApiPromiseHandler':
'prefix': 'reWithApiPromiseHandler'
'body': """
import withApiPromiseHandler from 'bundles/admin-dashboard-programs/components/members/withApiPromiseHandler';
"""
'reWithApiHandler':
'prefix': 'reWithApiHandler'
'body': """
import withApiHandler from 'bundles/admin-dashboard-programs/components/members/withApiHandler';
"""
'reWithApiNotificationFromStore':
'prefix': 'reWithApiNotificationFromStore'
'body': """
import withApiNotificationFromStore from 'bundles/admin-dashboard-programs/components/members/withApiNotificationFromStore';
"""
'reWithApiStatusUIInfo':
'prefix': 'reWithApiStatusUIInfo'
'body': """
import withApiStatusUIInfo from 'bundles/admin-dashboard-programs/components/members/withApiStatusUIInfo';
"""
'clo1':
'prefix': 'clo1'
'body': """
console.log('-- ${1:Component} --', this.props, this.state);
"""
'ireq-aphrodite':
'prefix': 'ireq-aphrodite'
'body': """
import { StyleSheet, css } from 'aphrodite';
"""
'req-aphrodite':
'prefix': 'req-aphrodite'
'body': """
import { StyleSheet, css } from 'aphrodite';
"""
'aph-template':
'prefix': 'aph-template'
'body': """
const styles = StyleSheet.create({
red: {
backgroundColor: 'red'
},
blue: {
backgroundColor: 'blue'
},
hover: {
':hover': {
backgroundColor: 'red'
}
},
small: {
'@media (max-width: 600px)': {
backgroundColor: 'red',
}
}
});
"""
'story-simple':
'prefix': 'story-simple'
'body': """
import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import { Divider } from 'src';
import { color } from 'src/styles/theme';
const DividerDemo = ({ isThemeDark }) => {
const containerStyle = isThemeDark ? {color: 'white', backgroundColor: '#363b42'} : {};
return (
<div className="m-b-2">
<h2>{isThemeDark ? 'Dark Theme' : 'Light Theme'}</h2>
<div className="p-a-1" style={containerStyle}>
<h3>Default</h3>
<div className="m-b-2">
<Divider />
</div>
</div>
</div>
);
};
storiesOf('basic.Divider', module)
.addWithInfo(
'simple usage',
`
Divider
~~~js
import { Divider } from 'coursera-ui';
<Divider />
<Divider isThemeDark />
~~~
`,
() => (
<div className="vertical-box p-t-3">
<DividerDemo />
<DividerDemo isThemeDark />
</div>
),
);
"""
'storyOf-withAddon':
'prefix': 'storyOf-withAddon'
'body': """
import Button from '../../../src/components/common/Button';
storiesOf('js.forms.withButtonProgress')
.addWithInfo(
'simple usage (custom propTables)',
`
This is the basic usage with the button with providing a label to show the text.
Since, the story source code is wrapped inside a div, info addon can't figure out propTypes on it's own.
So, we need to give relevant React component classes manually using \`propTypes\` option as shown below:
~~~js
storiesOf('Button')
.addWithInfo(
'simple usage (custom propTables)',
<info>,
<storyFn>,
{ inline: true, propTables: [Button]}
);
~~~
`,
() => (
<div>
<Button label="The Button" onClick={action('onClick')}/>
<br />
</div>
),
{ inline: true, propTables: [Button]}
);
"""
'hoc-class':
'prefix': 'hoc-class'
'body': """
const ${1:withApiHandler} = (Component) => {
const componentName = Component.displayName || Component.name;
return class ConnectedComponent extends React.Component {
displayName = `${1:withApiHandler}(${componentName})`;
state = {}
render() {
return (
<Component
{...this.props}
{...this.state}
/>
);
}
};
};
module.exports = ${1:withApiHandler};
"""
'hoc-stateless':
'prefix': 'hoc-stateless'
'body': """
const ${1:withApiHandler} = (Component) => {
const componentName = Component.displayName || Component.name;
const ${1:withApiHandler} = () => {
return (
<Component
{...this.props}
/>
);
}
${1:withApiHandler}.propTypes = {
name: React.PropTypes.string,
};
${1:withApiHandler}.displayName = `${1:withApiHandler}(${componentName})`;
return ${1:withApiHandler};
};
module.exports = ${1:withApiHandler};
"""
're-svgIcon':
'prefix': 're-svgIcon'
'body': """
const SvgIcon = require('bundles/admin-dashboard/components/svgIcons/SvgIcon');
<SvgIcon iconName="${1:SvgDownload}" size={${2:64}} className="color-primary" />
"""
're-svgIconButton':
'prefix': 're-svgIconButton'
'body': """
const SvgIconButton = require('bundles/admin-dashboard/components/svgIcons/SvgIconButton');
<SvgIconButton iconName="${1:SvgResend}" size={64} svgClassName="color-warn" handleClick={handleClick} />
"""
'naptimeMutation-delete':
'prefix': 'naptimeMutation-delete'
'body': """
getDeleteItemPromise: ({invitationId}) => {
return naptime.executeMutation(ProgramMembershipsV1.delete(
invitationId,
{body: {}}
));
},
"""
'naptimeMutation-action':
'prefix': 'naptimeMutation-action'
'body': """
getResendInvitationsPromise: ({invitationIds}) => {
return naptime.executeMutation(ProgramMembershipsV1.action(
'multiSend',
invitationIds,
{programId: program.id}
));
},
"""
'CourseStore':
'prefix': 'CourseStore'
'body': """
const CourseStore = fluxibleContext.getComponentContext().getStore('CourseStore');
const courseId = CourseStore.getCourseId();
"""
'fa-stack':
'prefix': 'fa-stack'
'body': """
<span className="fa-stack fa-lg">
<i className="fa fa-circle fa-stack-2x"></i>
<i className="fa fa-flag fa-stack-1x fa-inverse"></i>
</span>
"""
'connectToStoreApplication':
'prefix': 'connectToStoreApplication'
'body': """
connectToStores(
['ApplicationStore'],
({ApplicationStore}) => ({
userId: ApplicationStore.getUserData().id,
})
)
"""
'req-imgix':
'prefix': 'req-imgix'
'body': """
import Imgix from 'js/components/Imgix';
import imgixParams from 'bundles/page/common/imgixParams';
imgParams={imgixParams.fillWithWhiteBackground}
"""
'req-imgix-full':
'prefix': 'req-imgix-full'
'body': """
import Imgix from 'js/components/Imgix';
import imgixParams from 'bundles/page/common/imgixParams';
<Imgix
src={imgSrc}
alt={Imgix.DECORATIVE}
width={80}
height={80}
imgParams={imgixParams.fillWithWhiteBackground}
/>
"""
'req-config-asset':
'prefix': 'req-config-asset'
'body': """
import config from 'js/app/config';
const imagePath = `${config.url.assets}images/program-home/`;
"""
'eslint-prop-validatoin':
'prefix': 'eslint-prop-validatoin'
'body': """
/* eslint react/prop-types: 0 */
"""
'eslint-max-len':
'prefix': 'eslint-max-len'
'body': """
/* eslint-disable max-len */
"""
'rcc-short':
'prefix': 'rcc-short'
'body': """
class ${1:SearchInputWidget} extends React.Component {
render () {
return (
${2:}
);
}
}
"""
'propTypes':
'prefix': 'propTypes'
'body': """
static propTypes = {
${1:disableButton}: React.PropTypes.string,
}
"""
'React ES6 Component':
'prefix': 'rc'
'body': """
import React, { Component, PropTypes } from 'react';
export default class ${1:MyComponent} extends Component {
render() {
return (${2:<div>MyComponent</div>});
}
}
${1}.propTypes = {
};
"""
'React ES6 Component with Constructor':
'prefix': 'rcc'
'body': """
import React, { Component, PropTypes } from 'react';
class ${1:MyComponent} extends Component {
static propTypes = {
name: ''
}
constructor(props) {
super(props);
}
render() {
return (${2:<div>MyComponent</div>});
}
}
module.exports = ${1};
"""
'React ES6 Constructor':
'prefix': 'rconst'
'body': """
constructor(props) {
super(props);
${1}
}
"""
'React ES6 Functional Component':
'prefix': 'rfunc'
'body': """
import React, { PropTypes } from 'react';
export default function ${1}(props) {
return (
${2:<div>MyComponent</div>}
);
}
${1}.propTypes = {
};
"""
'React ES6 bind method to this':
'prefix': 'rbm',
'body': """
this.${1} = this.${1}.bind(this);
"""
'React ES6 props definition':
'prefix': 'rpd',
'body': """
${1}.propTypes = {
${2}
};
"""
# PropType string
'React PropType string':
'prefix': 'rpstr',
'body': "${1:myProp}: PropTypes.string,"
'React PropType string required':
'prefix': 'rpstrr',
'body': "${1:myProp}: PropTypes.string.isRequired,"
# PropType number
'React PropType number':
'prefix': 'rpn',
'body': "${1:myProp}: PropTypes.number,"
'React PropType number required':
'prefix': 'rpnr',
'body': "${1:myProp}: PropTypes.number.isRequired,"
# PropType object
'React PropType object':
'prefix': 'rpo',
'body': "${1:myProp}: PropTypes.object,"
'React PropType object required':
'prefix': 'rpor',
'body': "${1:myProp}: PropTypes.object.isRequired,"
# PropType array
'React PropType array':
'prefix': 'rpa',
'body': "${1:myProp}: PropTypes.array,"
'React PropType array required':
'prefix': 'rpar',
'body': "${1:myProp}: PropTypes.array.isRequired,"
# PropType bool
'React PropType bool':
'prefix': 'rpb',
'body': "${1:myProp}: PropTypes.bool,"
'React PropType bool required':
'prefix': 'rpbr',
'body': "${1:myProp}: PropTypes.bool.isRequired,"
# PropType element
'React PropType element':
'prefix': 'rpe',
'body': "${1:myProp}: PropTypes.element,"
'React PropType element required':
'prefix': 'rper',
'body': "${1:myProp}: PropTypes.element.isRequired,"
# PropType function
'React PropType function':
'prefix': 'rpf',
'body': "${1:myProp}: PropTypes.func,"
'React PropType function required':
'prefix': 'rpfr',
'body': "${1:myProp}: PropTypes.func.isRequired,"
# PropType shape
'React PropType shape':
'prefix': 'rps',
'body': """
${1:myProp}: PropTypes.shape({
${2}
}),
"""
'React PropType shape required':
'prefix': 'rpsr',
'body': """
${1:myProp}: PropTypes.shape({
${2}
}).isRequired,
"""
'comment':
'prefix': 'comment'
'body': '// TODO${1:(Audrey)}: ${2:}'
'clog-component':
'prefix': 'clog-component'
'body': """
console.log('--${1:Render}--'${2:,}${3:});
"""
'ircc':
'prefix': 'ircc'
'body': """
import React from 'react';
class LeaderboardApp extends React.Component {
render() {
return (
<div className="rc-LeaderboardApp">
LeaderboardApp
</div>
);
}
}
module.exports = LeaderboardApp;
"""
# Coursera
'React Class':
'prefix': 'rcc-lew'
'body': """
import React, {PropTypes} from 'react';
class ${1:[1. Component Name]} extends React.Component {
render() {
return (
<div className="rc-$1">
${2:[2. render body]}
</div>
);
}
}
module.exports = $1;
"""
'userId-':
'prefix': 'userId-'
'body': """
const userId = this.context.getStore('ApplicationStore').getUserData().id;
"""
'userId-store':
'prefix': 'userId-store'
'body': """
module.exports = connectToStores(
['ApplicationStore'],
({ApplicationStore}) => ({
userId: ApplicationStore.getUserData().id
})
)(${1:MembershipProvider});
"""
'epic enable':
'prefix': 'epic enable'
'body': """
import epic from 'bundles/epic/client';
${1:const enabled = }this.context.epic.get('UniversityProduct', '${2:enableDegreesUpsellInCatalog}');
"""
'fluxible-store':
'prefix': 'fluxible-store'
'body': """
import connectToStores from 'vendor/cnpm/fluxible.v0-4/addons/connectToStores';
const ConnectedProgramHome = connectToStores(
ProgramHomeApp,
['ProgramHomeStore'],
({ProgramHomeStore}, props) => ({
programMemberships: ProgramHomeStore.getProgramMemberships() || props.programMemberships,
program: _(props.programs).first(),
})
);
"""
'connectToStores':
'prefix': 'connectToStores'
'body': """
module.exports = connectToStores(
S12nNotEnrolledCard,
['S12nStore'],
({S12nStore}, {id}) => ({
firstCourse: S12nStore.getFirstCourseInS12nByS12nId(id),
})
);
"""
'naptime-container':
'prefix': 'naptime-container'
'body': """
Naptime.createContainer(
({${1:programSlug}}) => ({
programs: Programs.finder('slug', {
params: {slug: ${1:programSlug}},
fields: [
'slug',
'name',
'partnerIds',
'curriculum'
],
includes: [
'courseIds',
's12nIds',
'partnerIds',
],
subcomponents: [S12NCard, CourseCard, PartnerInfo]
}),
})
);
"""
'rcc-stateless':
'prefix': 'rcc-stateless'
'body': """
import React, {PropTypes} from 'react';
const ${1:App} = ({name = '${1:App}'}) => {
return (
<div className="rc-${1:App}">
<h1>${1:App} {name}</h1>
</div>
);
};
module.exports = ${1:App};
"""
'renaptime-store':
'prefix': 'renaptime-store'
'body': """
import NaptimeStore from 'bundles/natimejs/stores/NaptimeStore';
App.registerStore(NaptimeStore);
"""
'recss':
'prefix': 'recss'
'body': """
require('css!./__styles__/${1:TextInput}');
"""
're-common':
'prefix': 're-common'
'body': """
import React, { PropTypes } from 'react';
import _ from 'underscore';
import _t from 'i18n!nls/${1:program-home}';
const ${1:programs} = require('bundles/naptimejs/resources/${2:programs}.v1');
require('css!./__styles__/${3:AppName}');
"""
'retrans':
'prefix': 'retrans'
'body': """
import _t from 'i18n!nls/program-creation';
"""
'reunder':
'prefix': 'reunder'
'body': """
import _ from 'underscore';
"""
'recolor':
'prefix': 'recolor'
'body': """
@require 'bundles/styleguide/learnerApp/variables'
"""
# 'test-util':
# 'prefix': 'test-util'
# 'body': """
#
# """
'temp-selenium':
'prefix': 'temp-selenium'
'body': """
/* global browser */
const SELECTOR = {
programCourses: '.rc-ProgramCources',
programNavigation: '.rc-ProgramNavigation',
jumbotron: '.rc-ProgramJumbotron'
};
describe('[up]', function() {
it('program home should render for program member', function() {
return browser
.startFresh()
.asLearner()
.navigateTo('/programs/coursera-onboarding')
// Check for basic information
.assertElementExists(SELECTOR.jumbotron)
.assertElementExists(SELECTOR.programCourses)
.assertElementExists(SELECTOR.ProgramNavigation);
});
});
"""
########################## so-js
'.source.js':
'describe-behavior':
'prefix': 'describe-behavior'
'body': """
describe('${1:behaviors}', () => {
it('${2:should}', () => {
expect(true).to.equal(true);
});
});
"""
'describe-working':
'prefix': 'describe-working'
'body': """
describe('${1:working state}', () => {
it('${2:should work}', () => {
expect(true).to.equal(true);
});
});
"""
'describe-UI':
'prefix': 'describe-UI'
'body': """
describe('${1:UI render}', () => {
it('${2:should}', () => {
expect(true).to.equal(true);
});
});
"""
'describe-action':
'prefix': 'describe-action'
'body': """
describe('#${1:loadedProgram}', () => {
before(() => {
mockActionContext = {
dispatch: sinon.spy()
};
});
it('should will not call dispath if the payload format is invalid', () => {
const payload = {};
actions.${1:loadedProgram}(mockActionContext, payload);
expect(mockActionContext.dispatch.calledWith(
'${2:LOADED_PROGRAM}',
payload
)).to.equal(false);
});
it('should trigger ${2:LOADED_PROGRAM} with the payload', () => {
const payload = {${3:program}: {}};
actions.${1:loadedProgram}(mockActionContext, payload);
expect(mockActionContext.dispatch.calledWith(
'${2:LOADED_PROGRAM}',
payload
)).to.equal(true);
});
});
"""
'it-action-async':
'prefix': 'it-action-async'
'body': """
it('should trigger ENROLLED_SPECIALIZATION with after calling enrollInSpecialization api', (done) => {
const payload = {
programId:'p1',
s12nId: 's1',
userId: 1
};
actions.enrollSpecialization(mockActionContext, payload);
expect(stubs.enrollInSpecialization.calledOnce).to.equal(true);
stubs.enrollInSpecialization().then((data) => {
expect(mockActionContext.dispatch.calledWith(
'ENROLLED_SPECIALIZATION',{
s12nId: payload.s12nId,
userId: payload.userId,
}
)).to.equal(true);
done();
})
});
"""
'it-action-not':
'prefix': 'it-action-not'
'body': """
it('should will not call dispatch if the payload format is invalid', () => {
const payload = {};
actions.enrollSpecialization(mockActionContext, payload);
expect(mockActionContext.dispatch.calledWith(
'ENROLLED_SPECIALIZATION',
payload
)).to.equal(false);
});
"""
'xdescribe':
'prefix': 'xdescribe'
'body': """
xdescribe('${1:UnitName}', () => {
xit('${2:basic behaviors}', () => {
expect(true).to.equal(true);
});
});
"""
'it':
'prefix': 'it'
'body': """
it('should ${1:statement}', () => {
expect(true).to.equal(true);
});
"""
'it-invalid':
'prefix': 'it-invalid'
'body': """
it('should return undefined if the input is invalid', () => {
const invalidInput = null;
const output = ${1:programHomeUtils.getCourseAndProjectCounts}(invalidInput);
expect(output).to.equal(undefined);
});
"""
'it-valid':
'prefix': 'it-valid'
'body': """
it('${1:statement}', () => {
const validInput = ${2:validInput};
const output = programHomeUtils.getIsDarkThemeByColor(validInput);
expect(output).to.equal(${3:true});
});
"""
'wrapper-mock':
'prefix': 'wrapper-mock'
'body': """
wrapper = shallow(
<CatalogSearch
catalogResults={[new CatalogResultsV2({'entries': [{
id: 'some_other_id',
courseId: 'some_id',
specializationId: 'some_spec_Id',
onDemandSpecializationId: 'onDemandSpecializationId'}]
})]}
naptime={new Naptime.NaptimeProp({paging: {catalogResults: {total: 5}}})}
query={{}}
/>,
{context: {router: {location: {query: [{someQuery: 'val1'}]}}}}
);
"""
'esp-truthy':
'prefix': 'esp-truthy'
'body': """
expect(${1:wrapper.state('isModalVisible')}).toBeTruthy();
"""
'esp-falsy':
'prefix': 'esp-falsy'
'body': """
expect(${1:wrapper.state('isModalVisible')}).toBeFalsy();
"""
'esp-called':
'prefix': 'esp-called'
'body': """
expect(${1:propMock.onCloseModal}).toHaveBeenCalled();
"""
'espect-object':
'prefix': 'espect-object'
'body': """
expect(${1:output}).to.be.an('object');
"""
'test-ui':
'prefix': 'test-ui'
'body': """
/* eslint-disable no-undef */
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import ${1:CourseEnrolledDefaultCard} from '../${1:CourseEnrolledDefaultCard}';
describe('${1:CourseEnrolledDefaultCard}', () => {
let wrapper;
const propMock = {
course: {
id: 'c1',
name: 'cname',
photoUrl: 'http://photourl',
slug: 'cslug',
description: 'cdescription',
workload: 'cworkload',
homeLink: 'learn/clink',
partnerIds: [1],
isOnDemand: true,
},
};
describe('UI render', () => {
test('basic elements', () => {
wrapper = shallow(
<${1:CourseEnrolledDefaultCard} {...propMock} />
);
expect(toJson(wrapper)).toMatchSnapshot();
});
});
});
"""
'test-ui-behavior':
'prefix': 'test-ui-behavior'
'body': """u
/* eslint-disable no-undef */
import { shallow, mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import ${1:SessionSwitchCard} from '../${1:SessionSwitchCard}';
describe('${1:SessionSwitchCard}', () => {
let wrapper;
const propMock = {
onCloseModal: jest.fn(),
onShowModal: jest.fn(),
isModalVisible: false,
courseId: 'c1'
};
describe('UI render', () => {
test('basic elements', () => {
wrapper = shallow(
<${1:SessionSwitchCard} {...propMock} />
);
expect(toJson(wrapper)).toMatchSnapshot();
});
});
describe('behaviors', () => {
test('should set isModalVisible to false and call onCloseModal when handleCloseModal is called', () => {
wrapper = mount(
<${1:SessionSwitchCard} {...propMock} />
);
wrapper.instance().handleCloseModal();
expect(wrapper.state('isModalVisible')).toBeFalsy();
expect(propMock.onCloseModal).toHaveBeenCalled();
});
});
});
"""
'Component test':
'prefix': 'testcomp'
'body': """
const shallow = require('enzyme').shallow;
const expect = require('chai').expect;
const sinon = require('sinon');
const setup = require('static/bundles/test/componentSetup');
/* globals React */
describe('${1:[1. Component Name]}', () => {
setup();
let wrapper;
before(() => {
const ${1:[1. Component Name]} = environment.require('${2:[2. Path to component]}');
wrapper = shallow(
<${1:[1. Component Name]} />
);
});
describe('#render', () => {
it('${3:[3. Statement]}');
});
});
"""
'Generic test':
'prefix': 'testgen'
'body': """
const setup = require('static/bundles/test/genericSetup');
const expect = require('chai').expect;
describe('${1:[1. module name]}', () => {
setup();
before(() => {
const ${1:[1. module name]} = environment.require('${2:[2. Path to module]}')
});
it('${3: should be correct}', () => {
expect(true).to.equal(false)
});
});
"""
'Environment require':
'prefix': 'envrequire'
'body': """environment.require('$1')"""
'test-tem-subscriptionEnrollButton':
'prefix': 'test-tem-subscriptionEnrollButton'
'body': """
/* globals SubscriptionEnrollButton, React */
/* eslint-disable no-unused-expressions */
const Q = require('q');
const {expect} = require('chai');
const {shallow} = require('enzyme');
const setup = require('static/bundles/test/componentSetup');
const sinon = require('sinon');
describe('SubscriptionEnrollButton', () => {
setup();
let wrapper;
let trackStub;
let executeActionStub;
const s12nId = 'S12nId - Am I still a kangaroo?';
beforeEach(() => {
trackStub = sinon.stub();
executeActionStub = sinon.stub();
executeActionStub.returns(Q());
wrapper = shallow(<SubscriptionEnrollButton />,
{context: {track: trackStub, executeAction: executeActionStub, s12nId}});
});
describe('on clicking the enrollment button', () => {
beforeEach(() => {
wrapper.find('button').simulate('click');
});
it('should call tracking once', () => {
expect(trackStub.calledOnce).to.be.true;
});
it('should call execute action', () => {
expect(executeActionStub.calledOnce).to.be.true;
});
});
});
"""
'test-tem-walletForm':
'prefix': 'test-tem-walletForm'
'body': """
/* eslint-disable no-unused-expressions */
const {expect} = require('chai');
const {render, shallow} = require('enzyme');
const setup = require('static/bundles/test/componentSetup');
describe('WalletForm', () => {
setup();
let wrapper;
let wallet;
beforeEach(() => {
wallet = require('./fixtures/WalletData');
});
describe('it renders the correct elements in the form (shallow)', () => {
beforeEach(() => {
wrapper = shallow(<WalletForm wallet={wallet} />, {context: {executeAction: () => {}}});
});
it('does not contains store credit card', () => {
expect(wrapper.find('StoreCreditCardPreference')).to.have.length(0);
});
it('renders only one InputForm group for the credit card name', () => {
expect(wrapper.find('InputFormGroup')).to.have.length(1);
});
it('renders only one Expiration Form', () => {
expect(wrapper.find('ExpirationFormGroup')).to.have.length(1);
});
it('renders only one LocationFormGroup Form', () => {
expect(wrapper.find('LocationFormGroup')).to.have.length(1);
});
});
describe('it renders the correct elements in the form', () => {
beforeEach(() => {
wrapper = render(<WalletForm wallet={wallet} />, {context: {executeAction: () => {}}});
});
it('contains the credit card number exed out', () => {
expect(wrapper.html()).to.contain(`XXXX-XXXX-XXXX-${wallet.creditCardLastFourDigits}`);
});
it('contains one disabled input form', () => {
expect(wrapper.find('input[disabled]')).to.have.length(1);
});
it('contains three disabled select form', () => {
expect(wrapper.find('select[disabled]')).to.have.length(3);
});
});
});
"""
'test-tem-paymentCheckoutStore':
'prefix': 'test-tem-paymentCheckoutStore'
'body': """
const expect = require('chai').expect;
const sinon = require('sinon');
const setup = require('static/bundles/test/genericSetup');
describe('PaymentCheckoutStore', () => {
setup();
let PaymentCheckoutStore;
let store;
let getStoreStub;
let paymentMethods;
beforeEach(() => {
PaymentCheckoutStore = environment.require('bundles/payments/stores/PaymentCheckoutStore');
paymentMethods = environment.require('bundles/payments/constants').paymentMethods;
store = new PaymentCheckoutStore();
getStoreStub = sinon.stub();
store.dispatcher = {getStore: getStoreStub};
});
describe('SET_PAYMENT_METHOD', () => {
it('should have the correct default value', () => {
expect(store.getPaymentMethod()).to.be.equal('card');
});
it('should set a valid method', () => {
PaymentCheckoutStore.handlers.SET_PAYMENT_METHOD.call(store, 'paypal');
expect(store.getPaymentMethod()).to.be.equal('paypal');
});
it('should not allow an invalid payment method', () => {
PaymentCheckoutStore.handlers.SET_PAYMENT_METHOD.call(store, 'A unicorn!');
expect(store.getPaymentMethod()).to.be.equal('card');
});
});
describe('Initial state should be correctly set up', () => {
it('should not show confirmation page', () => {
expect(store.getShowConfirmationPage()).to.be.false;
});
it('should not be submittiing', () => {
expect(store.getIsSubmittingPayment()).to.be.false;
});
it('should not have errors', () => {
expect(store.getFormHasError()).to.be.false;
});
it('should have card set as a payment method', () => {
expect(store.getPaymentMethod()).to.be.equal('card');
});
it('should not use sandbox', () => {
expect(store.getUseSandbox()).to.be.false;
});
});
describe('getPaymentMethodStore works as expected', () => {
beforeEach(() => {
Object.keys(paymentMethods).map((paymentMethod) => {
store.paymentMethod = paymentMethods[paymentMethod];
store.getPaymentMethodStore();
});
});
it('should call getStoreStub for each payment method', () => {
expect(getStoreStub.callCount).to.be.equal(Object.keys(paymentMethods).length);
});
it('should call the stores in the correct order', () => {
expect(getStoreStub.args).to.be.deep.equal(
[['BraintreeFormStore'], ['PaypalFormStore'], ['StripeFormStore'], ['WalletFormStore'], ['ZeroPaymentStore']]);
});
});
"""
'test-tem-async-behavior':
'prefix': 'test-tem-async-behavior'
'body': """
describe('async behaviors', () => {
it('should call handleDismiss after the dismissTimer', () => {
const handleDismissStub = sinon.stub();
const setTimeoutStub = sinon.stub(global, 'setTimeout', (fn, timeout) => {
fn();
});
wrapper = mount(
<AlertWidget
handleDismiss={handleDismissStub}
message={'abc'}
dismissAfter={10}
/>
);
// wrapper.instance().componentDidMount.call(wrapper.instance());
expect(setTimeoutStub.calledWith(handleDismissStub, 10)).to.equal(true);
expect(handleDismissStub.called).to.equal(true);
setTimeoutStub.restore();
});
});
"""
'test-tem-action':
'prefix': 'test-tem-action'
'body': """
const setup = require('static/bundles/test/genericSetup');
const sinon = require('sinon');
const expect = require('chai').expect;
const courseId = 'SOME_COURSE_ID';
const messageKey = 'SOME_MESSAGE_KEY';
describe('SessionSetupActions#clearAllSessions - success', () => {
setup();
let mockActionContext;
before((done) => {
const Q = require('q');
environment.define('bundles/author-course/actions/CourseActionCreators', () => ({
getCourse: () => Q()
}));
environment.define('bundles/author-course/utils/CourseSessionAPIUtils', () => ({
clearAllSessions: () => Q()
}));
environment.define('bundles/author-common/utils/CourseAPIUtils', () => ({
getCourse: () => ({})
}));
environment.define('bundles/author-course/actions/CourseServerActionCreators', () => ({
receiveCourse: (data) => ({})
}));
mockActionContext = {
dispatch: sinon.stub(),
executeAction: sinon.spy(() => Q())
};
const SessionSetupActions = environment.require('bundles/author-sessions/actions/SessionSetupActions');
SessionSetupActions.clearAllSessions(mockActionContext, {courseId, messageKey}, done);
});
it('should dispatch CLEAR_ALL_SESSIONS', () => {
expect(mockActionContext.dispatch.calledWith('CLEAR_ALL_SESSIONS')).to.equal(true);
});
it('should dispatch CLEAR_SESSION_SCHEDULER', () => {
expect(mockActionContext.dispatch.calledWith('CLEAR_SESSION_SCHEDULER')).to.equal(true);
});
it('should execute deleteCurrentScheduler', () => {
const { deleteCurrentScheduler } = environment.require('bundles/author-sessions/actions/SessionSchedulerActions');
expect(mockActionContext.executeAction.calledWith(deleteCurrentScheduler)).to.eql(true);
});
});
describe('#SessionSetupActions#clearAllSessions - server error', () => {
setup();
let mockActionContext;
let responseJSON;
before((done) => {
const Q = require('q');
responseJSON = {
errors: [{
errorCode: 'Wat',
fieldName: 'Wat',
msg: 'Wat',
details: 'Wat'
}]
};
environment.define('bundles/author-course/actions/CourseActionCreators', () => ({
getCourse: () => Q()
}));
environment.define('bundles/author-course/utils/CourseSessionAPIUtils', () => ({
clearAllSessions: () => Q.reject({ responseJSON })
}));
environment.define('bundles/author-common/utils/CourseAPIUtils', () => ({
getCourse: () => ({})
}));
environment.define('bundles/author-course/actions/CourseServerActionCreators', () => ({
receiveCourse: (data) => ({})
}));
mockActionContext = {
executeAction: sinon.spy(() => Q()),
dispatch: () => ({})
};
const SessionSetupActions = environment.require('bundles/author-sessions/actions/SessionSetupActions');
SessionSetupActions.clearAllSessions(mockActionContext, {courseId, messageKey}, done);
});
describe('server error case', () => {
it('should execute setServerErrorMessage', () => {
const { setServerErrorMessage } = environment.require('bundles/phoenix/components/ConnectedInlineMessage');
expect(mockActionContext.executeAction
.calledWith(setServerErrorMessage, {
messageKey,
contents: {
responseJSON
}
})
).to.eql(true);
});
});
});
describe('#SessionSetupActions#clearAllSessions - error', () => {
setup();
let mockActionContext;
before((done) => {
const Q = require('q');
environment.define('bundles/author-course/actions/CourseActionCreators', () => ({
getCourse: () => Q()
}));
environment.define('bundles/author-common/utils/CourseAPIUtils', () => ({
getCourse: () => ({})
}));
environment.define('bundles/author-course/actions/CourseServerActionCreators', () => ({
receiveCourse: (data) => ({})
}));
environment.define('bundles/author-course/utils/CourseSessionAPIUtils', () => ({
clearAllSessions: () => Q.reject({
message: 'Wat'
})
}));
mockActionContext = {
executeAction: sinon.spy(() => Q()),
dispatch: () => ({})
};
const SessionSetupActions = environment.require('bundles/author-sessions/actions/SessionSetupActions');
SessionSetupActions.clearAllSessions(mockActionContext, {courseId, messageKey}, done);
});
describe('error case', () => {
it('should execute setErrorMessage', () => {
const { setErrorMessage } = environment.require('bundles/phoenix/components/ConnectedInlineMessage');
expect(mockActionContext.executeAction
.calledWith(setErrorMessage, {
messageKey,
contents: 'Wat'
})
).to.eql(true);
});
});
});
"""
'espect-wrapper-call':
'prefix': 'espect-wrapper-call'
'body': """
wrapper.instance().componentDidMount.call(wrapper.instance());
"""
'espect-context-stub':
'prefix': 'espect-context'
'body': """
before(() => {
wrapper = shallow(<CirclesMenuWidget {...propMock} />, {
context: {
getStore: (storeName) => {
return {
getUserData: () => {
return {
id: 1
};
}
};
}
}
});
});
"""
'espect-sinon-static-stub':
'prefix': 'espect-sinon-static-stub'
'body': """
getCardStateLocalStub = sinon.stub(CircleWithCourseProgressWidget, 'getCardStateLocal', () => 'green-cover');
"""
'espect-before':
'prefix': 'espect-before'
'body': """
before(() => {
wrapper = shallow(
<${1:CourseInfoColumn} />
);
"""
'clog-debug':
'prefix': 'clog-debug'
'body': """
console.log(wrapper.debug());
"""
'clog':
'prefix': 'clog'
'body': """
console.log('--${1:Component}--'${2:, }${3: x});
"""
# tests
'tem-test-util':
'prefix': 'tem-test-util'
'body': """
const setup = require('static/bundles/test/genericSetup');
const expect = require('chai').expect;
describe('formValidation', () => {
setup();
let email;
before(() => {
email = environment.require('bundles/program-admin/utils/formValidation').email;
});
it('email validation', () => {
expect(email('[email protected]')).to.equal(undefined);
});
});
"""
'tem-test-component-full':
'prefix': 'tem-test-component-full'
'body': """
const shallow = require('enzyme').shallow;
const expect = require('chai').expect;
const sinon = require('sinon');
const setup = require('static/bundles/test/componentSetup');
/* globals React */
describe('ProgramSettings', () => {
setup();
let wrapper;
let Programs;
let ProgramSettings;
before(() => {
ProgramSettings = environment.require('bundles/program-admin/components/ProgramSettings');
Programs = environment.require('bundles/naptimejs/resources/programs.v1');
wrapper = shallow(
<ProgramSettings
program={new Programs({
program: {
definition: {
metadata: {
description: {
definition: {
value: 'ASDFASDF'
}
}
}
}
}
})}
/>
);
});
describe('#constructor', () => {
it('should call _setStateByProgram');
});
describe('#handleDismiss', () => {
it('should set showAlert to false');
});
describe('#handleChange', () => {
it('should set input to dirty if the value does not equal the default value');
it('should set the input to error if there are any validation errors');
it('should set input to touched if its been touched');
it('should call _addValidationResultToState');
});
describe('#_addValidationResultToState', () => {
});
describe('#render', () => {
it('should render AlertWidget with alertInfo showAlert: true', () => {
wrapper.setState({ showAlert: true });
expect(wrapper.find('AlertWidget').length)
.to.equal(1);
});
xit('should render AlertWidget with a Saving... message if isFormSubmitting: true', () => {
wrapper.setState({ isFormSubmitting: true });
expect(wrapper.find('AlertWidget').prop('message'))
.to.contain('Saving');
});
});
});
describe('ProgramSettings with successful updateProgramSettings', () => {
setup();
let updateProgramSettingsStub;
let setStateByProgramSpy;
let ProgramSettings;
let Programs;
let wrapper;
before(() => {
const Q = environment.require('q');
const ProgramAdminAPIUtilsMock = {
updateProgramSettings: (programId, newProgram) => Q({
data: {
elements: [{
program: {}
}]
}
})
};
updateProgramSettingsStub = sinon.spy(ProgramAdminAPIUtilsMock, 'updateProgramSettings');
environment.define('bundles/program-admin/utils/ProgramAdminAPIUtils', () => ProgramAdminAPIUtilsMock);
Programs = environment.require('bundles/naptimejs/resources/programs.v1');
ProgramSettings = environment.require('bundles/program-admin/components/ProgramSettings');
wrapper = shallow(
<ProgramSettings
program={new Programs({
program: {
definition: {
metadata: {
description: {
definition: {
value: 'ASDFASDF'
}
}
}
}
}
})}
/>
);
});
describe('#handleSubmit', () => {
before(() => {
wrapper.find('button[type="submit"]').simulate('submit', {
preventDefault: () => {}
});
});
it('should set isFormSubmittedToFalse');
it('should call updateProgramSettings', () => {
expect(updateProgramSettingsStub.callCount).to.equal(1);
});
it('should call _setStateByProgram', (done) => {
setStateByProgramSpy = sinon.stub(wrapper.instance(), '_setStateByProgram', () => {
done();
});
expect(setStateByProgramSpy.callCount).to.equal(1);
});
});
});
"""
# General
'rer':
'prefix': 'rer'
'body': """
import React from 'react';
"""
'rerp':
'prefix': 'rerp'
'body': """
import React, { PropTypes } from 'react';
"""
'rercp':
'prefix': 'rercp'
'body': """
import React, { Component, PropTypes } from 'react';
"""
'req-errorMessage':
'prefix': 'req-errorMessage'
'body': """
import ErrorMessage from 'bundles/coursera-ui/components/extended/ErrorMessage';
{error && <ErrorMessage error={error} defaultErrorMsg={DEFAULT_ERROR_MSG} />}
"""
'req-naptime':
'prefix': 'req-naptime'
'body': """
import Naptime from 'naptime';
"""
'naptime-prop':
'prefix': 'naptime-prop'
'body': """
naptime: PropTypes.instanceOf(Naptime.NaptimeProp),
"""
'req-short':
'prefix': 'req-short'
'body': """
const ${1:App} = require('${1:App}');
"""
'req-classnames':
'prefix': 'req-classnames'
'body': """
import classNames from 'classnames';
"""
'ireq-classname':
'prefix': 'ireq-classname'
'body': """
import cn from 'classnames';
"""
'req-translate':
'prefix': 'req-translate'
'body': """
import _t from 'i18n!nls/${1:teams}';
"""
'req-redirect':
'prefix': 'req-redirect'
'body': """
import redirect from 'js/lib/coursera.redirect';
"""
'req-retracked':
'prefix': 'req-retracked'
'body': """
import Retracked from 'js/lib/retracked';
"""
'req-connectToStore':
'prefix': 'req-connectToStore'
'body': """
import connectToStores from 'vendor/cnpm/fluxible.v0-4/addons/connectToStores';
"""
'req-connectToRouter':
'prefix': 'req-connectToRouter'
'body': """
import connectToRouter from 'js/lib/connectToRouter';
"""
# Enzyme
# Custom
'test-shallow':
'prefix': 'test-shallow'
'body': """
wrapper = shallow(<${1:MyComponent} {...propMock} />);
"""
'test-shallow-context':
'prefix': 'test-shallow-context'
'body': """
wrapper = shallow(<${1:S12nCardExtended} {...propMock} />, {
context: {
executeAction: () => {},
getStore: (storeName) => {
return {
getUserData: () => {
return {
id: 1
};
}
};
}
}
});
"""
'test-tem-async-timer':
'prefix': 'test-tem-async-timer'
'body': """
describe('async behaviors', () => {
it('should call handleDismiss after the dismissTimer', () => {
const handleDismissStub = sinon.stub();
const setTimeoutStub = sinon.stub(global, 'setTimeout', (fn, timeout) => {
fn();
});
wrapper = mount(
<AlertWidget
handleDismiss={handleDismissStub}
message={'abc'}
dismissAfter={10}
/>
);
expect(setTimeoutStub.calledWith(handleDismissStub, 10)).to.equal(true);
expect(handleDismissStub.called).to.equal(true);
setTimeoutStub.restore();
});
});
"""
'espe-prop-property':
'prefix': 'espe-prop-property'
'body': """
expect(wrapper.prop('style')).to.have.property('width', '44px');
"""
# Library
'espe-at':
'prefix': 'espe-at'
'body': """
expect(wrapper.find(Foo).at(0).props().foo).to.equal("bar");
"""
'espe-childAt':
'prefix': 'espe-childAt'
'body': """
const wrapper = shallow(<ToDoList items={items} />);
expect(wrapper.find('ul').childAt(0).type()).to.equal('li');
"""
'espe-children':
'prefix': 'espe-children'
'body': """
expect(wrapper.children()).to.have.length(0);
"""
'espe-closest':
'prefix': 'espe-closest'
'body': """
expect(wrapper.find(Foo).closest('.bar')).to.have.length(1);
"""
'
expect-contains':
'prefix': 'espe-contains'
'body': """
const wrapper = shallow(<MyComponent />);
expect(wrapper.contains(<div className="foo bar" />)).to.equal(true);
"""
'espe-contains-long':
'prefix': 'espe-contains-long'
'body': """
const wrapper = shallow(
<div>
<span>Hello</span>
<div>Goodbye</div>
<span>Again</span>
</div>
);
expect(wrapper.contains([
<span>Hello</span>,
<div>Goodbye</div>,
])).to.equal(true);
"""
'espe-containsMatchingElement':
'prefix': 'espe-containsMatchingElement'
'body': """
const MyComponent = React.createClass({
handleClick() {
...
},
render() {
return (
<div>
<div onClick={this.handleClick} className="foo bar">Hello</div>
</div>
);
}
});
const wrapper = shallow(<MyComponent />);
expect(wrapper.containsMatchingElement(
<div>Hello</div>
)).to.equal(true);
expect(wrapper.containsMatchingElement(
<div className="foo bar">Hello</div>
)).to.equal(true);
"""
'espe-containsAllMatchingElement':
'prefix': 'espe-containsAllMatchingElement'
'body': """
const wrapper = shallow(
<div>
<span className="foo">Hello</span>
<div style={{ fontSize: 13 }}>Goodbye</div>
<span>Again</span>
</div>
);
expect(wrapper.containsAllMatchingElements([
<span>Hello</span>,
<div>Goodbye</div>,
])).to.equal(true);
"""
'espe-containsAnyMatchingElement':
'prefix': 'espe-containsnyMMatchingElement'
'body': """
const wrapper = shallow(
<div>
<span className="foo">Hello</span>
<div style={{ fontSize: 13 }}>Goodbye</div>
<span>Again</span>
</div>
);
expect(wrapper.containsAnyMatchingElements([
<span>Bonjour</span>,
<div>Goodbye</div>,
])).to.equal(true);
"""
'espe-context':
'prefix': 'espe-context'
'body': """
expect(wrapper.context('foo')).to.equal(10);
"""
'espe-debug':
'prefix': 'espe-debug'
'body': """
console.log(wrapper.debug());
"""
'espe-debug-full':
'prefix': 'espe-debug-full'
'body': """
console.log(mount(<Bar id="2" />).find(Foo).debug());
"""
'espe-equals':
'prefix': 'espe-equals'
'body': """
expect(wrapper.equals(<div className="foo bar" />)).to.equal(true);
"""
'espe-every':
'prefix': 'espe-every'
'body': """
const wrapper = shallow(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').every('.foo')).to.equal(true);
expect(wrapper.find('.foo').every('.qoo')).to.equal(false);
expect(wrapper.find('.foo').every('.bar')).to.equal(false);
"""
'espe-everyWhere':
'prefix': 'espe-everyWhere'
'body': """
const wrapper = shallow(
<div>
<div className="foo qoo" />
<div className="foo boo" />
<div className="foo hoo" />
</div>
);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('foo'))).to.equal(true);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('qoo'))).to.equal(false);
expect(wrapper.find('.foo').everyWhere(n => n.hasClass('bar'))).to.equal(false);
"""
'espe-filter':
'prefix': 'espe-filter'
'body': """
expect(wrapper.find('.foo').filter('.bar')).to.have.length(1);
"""
'espe-filterWhere':
'prefix': 'espe-filterWhere'
'body': """
const complexFoo = wrapper.find('.foo').filterWhere(n => typeof n.type() !== 'string');
expect(complexFoo).to.have.length(4);
"""
'espe-find':
'prefix': 'espe-find'
'body': """
expect(wrapper.find('${1:App}')).to.have.length(1);
"""
'espe-findWhere':
'prefix': 'espe-findWhere'
'body': """
const complexComponents = wrapper.findWhere(n => typeof n.type() !== 'string');
expect(complexComponents).to.have.length(8);
"""
'espe-first':
'prefix': 'espe-first'
'body': """
expect(wrapper.find(Foo).first().props().foo).to.equal("bar");
"""
'espe-last':
'prefix': 'espe-last'
'body': """
expect(wrapper.find(Foo).last().props().foo).to.equal("bar");
"""
'espe-forEach':
'prefix': 'espe-forEach'
'body': """
const wrapper = shallow(
<div>
<div className="foo bax" />
<div className="foo bar" />
<div className="foo baz" />
</div>
);
wrapper.find('.foo').forEach(function (node) {
expect(node.hasClass('foo')).to.equal(true);
});
"""
'espe-get':
'prefix': 'espe-get'
'body': """
expect(wrapper.find(Foo).get(0).props.foo).to.equal("bar");
"""
'espe-hasClass':
'prefix': 'espe-hasClass'
'body': """
expect(wrapper.find('.my-button').hasClass('disabled')).to.equal(true);
"""
'espe-html':
'prefix': 'espe-html'
'body': """
expect(wrapper.html()).to.equal('<div><b>important</b></div>');
"""
'espe-instance':
'prefix': 'espe-instance'
'body': """
const inst = wrapper.instance();
expect(inst).to.be.instanceOf(MyComponent);
"""
'espe-is':
'prefix': 'espe-is'
'body': """
const wrapper = shallow(<div className="some-class other-class" />);
expect(wrapper.is('.some-class')).to.equal(true);
"""
'espe-key':
'prefix': 'espe-key'
'body': """
const wrapper = shallow(
<ul>
{['foo', 'bar'].map(s => <li key={s}>{s}</li>)}
</ul>
).find('li');
expect(wrapper.at(0).key()).to.equal('foo');
expect(wrapper.at(1).key()).to.equal('bar');
"""
'espe-map':
'prefix': 'espe-map'
'body': """
const wrapper = shallow(
<div>
<div className="foo">bax</div>
<div className="foo">bar</div>
<div className="foo">baz</div>
</div>
);
const texts = wrapper.find('.foo').map(node => node.text());
expect(texts).to.eql([ 'bax', 'bar', 'baz' ]);
"""
'espe-matchesElement':
'prefix': 'espe-matchesElement'
'body': """
const MyComponent = React.createClass({
handleClick() {
...
},
render() {
return (
<div onClick={this.handleClick} className="foo bar">Hello</div>
);
}
});
const wrapper = shallow(<MyComponent />);
expect(wrapper.matchesElement(
<div>Hello</div>
)).to.equal(true);
expect(wrapper.matchesElement(
<div className="foo bar">Hello</div>
)).to.equal(true);
"""
'espe-name':
'prefix': 'espe-name'
'body': """
Foo.displayName = 'A cool custom name';
const SomeWrappingComponent = () => <Foo />;
const wrapper = shallow(<SomeWrappingComponent />);
expect(wrapper.name()).to.equal('A cool custom name');
"""
'espe-not':
'prefix': 'espe-not'
'body': """
expect(wrapper.find('.foo').not('.bar')).to.have.length(1);
"""
'espe-parent':
'prefix': 'espe-parent'
'body': """
expect(wrapper.find('ul').parent().is('div')).to.equal(true);
"""
'espe-parents':
'prefix': 'espe-parents'
'body': """
expect(wrapper.find('ul').parents()).to.have.length(2);
"""
'espe-prop':
'prefix': 'espe-prop'
'body': """
expect(wrapper.prop('foo')).to.equal(10);
"""
'espe-props':
'prefix': 'espe-props'
'body': """
expect(wrapper.props().foo).to.equal(10);
"""
'espe-reduce':
'prefix': 'espe-reduce'
'body': """
const total = wrapper.find(Bar).reduce((amount, n) => amount + n.prop('amount'));
expect(total).to.equal(16)
"""
'espe-render':
'prefix': 'espe-render'
'body': """
expect(wrapper.find('.in-foo')).to.have.length(0);
expect(wrapper.find(Foo).render().find('.in-foo')).to.have.length(1);
"""
'espe-setContext':
'prefix': 'espe-setContext'
'body': """
wrapper.setContext({ name: 'bar' });
"""
'espe-setProps':
'prefix': 'espe-setProps'
'body': """
wrapper.setProps({${1:foo: 'foo'}});
"""
'espe-setProps-example':
'prefix': 'espe-setProps-long'
'body': """
const spy = sinon.spy(MyComponent.prototype, 'componentWillReceiveProps');
const wrapper = shallow(<MyComponent foo="bar" />);
expect(spy.calledOnce).to.equal(false);
wrapper.setProps({ foo: 'foo' });
expect(spy.calledOnce).to.equal(true);
"""
'espe-setState':
'prefix': 'espe-setState'
'body': """
wrapper.setState({${1:foo: 'foo'}});
"""
'espe-shallow':
'prefix': 'espe-shallow'
'body': """
expect(wrapper.find('.in-bar')).to.have.length(0);
expect(wrapper.find(Bar)).to.have.length(1);
expect(wrapper.find(Bar).shallow().find('.in-bar')).to.have.length(1);
"""
'espe-simulate':
'prefix': 'espe-simulate'
'body': """
wrapper.find(${1:'a'}).simulate('click');
"""
'espe-some':
'prefix': 'espe-some'
'body': """
expect(wrapper.find('.foo').some('.qoo')).to.equal(true);
"""
'espe-someWhere':
'prefix': 'espe-someWhere'
'body': """
expect(wrapper.find('.foo').someWhere(n => n.hasClass('qoo'))).to.equal(true);
"""
'espe-state':
'prefix': 'espe-state'
'body': """
expect(wrapper.state().${1:foo}).to.equal(10);
"""
'espe-test':
'prefix': 'espe-test'
'body': """
expect(wrapper.text()).to.equal('${1:<Foo />important}');
"""
'espe-type':
'prefix': 'espe-type'
'body': """
expect(wrapper.type()).to.equal(${1:Bar});
"""
'espe-type-null':
'prefix': 'espe-type-null'
'body': """
expect(wrapper.type()).to.equal(null);
"""
'espe-unmount-example':
'prefix': 'espe-unmount-example'
'body': """
const wrapper = shallow(<Foo id="foo" />);
expect(spy.calledOnce).to.equal(false);
wrapper.unmount();
expect(spy.calledOnce).to.equal(true);
"""
'espe-update-example':
'prefix': 'espe-update-example'
'body': """
expect(wrapper.text()).to.equal("0");
wrapper.update();
expect(wrapper.text()).to.equal("1");
"""
'espe-detach-attach-example':
'prefix': 'espe-detach-attach-example'
'body': """
// create a div in the document to mount into
const div = global.document.createElement('div');
global.document.body.appendChild(div);
// div is empty. body has the div attached.
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
// mount a component passing div into the `attachTo` option
const wrapper = mount(<Foo />, { attachTo: div });
// we can see now the component is rendered into the document
expect(wrapper.find('.in-foo')).to.have.length(1);
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(1);
// call detach to clean up
wrapper.detach();
// div is now empty, but still attached to the document
expect(document.body.childNodes).to.have.length(1);
expect(div.childNodes).to.have.length(0);
// remove div if you want
global.document.body.removeChild(div);
expect(document.body.childNodes).to.have.length(0);
expect(div.childNodes).to.have.length(0);
"""
'espe-html-example':
'prefix': 'espe-html-example'
'body': """
const wrapper = mount(<Bar />);
expect(wrapper.html()).to.equal(
`<div class="in-bar"><div class="in-foo"></div></div>`
);
expect(wrapper.find(Foo).html()).to.equal(
`<div class="in-foo"></div>`
);
"""
'espe-mount-example':
'prefix': 'espe-mount-example'
'body': """
const willMount = sinon.spy();
const didMount = sinon.spy();
const willUnmount = sinon.spy();
class Foo extends React.Component {
constructor(props) {
super(props);
this.componentWillUnmount = willUnmount;
this.componentWillMount = willMount;
this.componentDidMount = didMount;
}
render() {
return (
<div className={this.props.id}>
{this.props.id}
</div>
);
}
}
const wrapper = mount(<Foo id="foo" />);
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(0);
wrapper.unmount();
expect(willMount.callCount).to.equal(1);
expect(didMount.callCount).to.equal(1);
expect(willUnmount.callCount).to.equal(1);
wrapper.mount();
expect(willMount.callCount).to.equal(2);
expect(didMount.callCount).to.equal(2);
expect(willUnmount.callCount).to.equal(1);
"""
'espe-ref':
'prefix': 'espe-ref'
'body': """
expect(wrapper.ref('${1:SecondRef}').text()).to.equal('${2:Second}');
"""
'espe-tem-fulldom':
'prefix': 'espe-tem-full-dom'
'body': """
import { mount } from 'enzyme';
describe('<Foo />', () => {
it('calls componentDidMount', () => {
spy(Foo.prototype, 'componentDidMount');
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true);
});
it('allows us to set props', () => {
const wrapper = mount(<Foo bar="baz" />);
expect(wrapper.props().bar).to.equal("baz");
wrapper.setProps({ bar: "foo" });
expect(wrapper.props().bar).to.equal("foo");
});
it('simulates click events', () => {
const onButtonClick = spy();
const wrapper = mount(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.equal(true);
});
});
"""
'espe-tem-shallow':
'prefix': 'espe-tem-shallow'
'body': """
import { shallow } from 'enzyme';
describe('<MyComponent />', () => {
it('should render three <Foo /> components', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find(Foo)).to.have.length(3);
});
it('should render an `.icon-star`', () => {
const wrapper = shallow(<MyComponent />);
expect(wrapper.find('.icon-star')).to.have.length(1);
});
it('should render children when passed in', () => {
const wrapper = shallow(
<MyComponent>
<div className="unique" />
</MyComponent>
);
expect(wrapper.contains(<div className="unique" />)).to.equal(true);
});
it('simulates click events', () => {
const onButtonClick = sinon.spy();
const wrapper = shallow(
<Foo onButtonClick={onButtonClick} />
);
wrapper.find('button').simulate('click');
expect(onButtonClick.calledOnce).to.equal(true);
});
});
"""
'test-callcdm':
'prefix': 'test-callcdm'
'body': """
it('calls componentDidMount', () => {
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true);
});
"""
'test-selenium-tem-epic':
'prefix': 'test-selenium-tem-epic'
'body': """
/* global browser */
const SELECTOR = {
programLandingPage: '.rc-ProgramLandingPage',
requestInfoButton: '.rc-AboutProgram .buttonQuestion a',
surveySection: '.rc-SurveySection'
};
const PROGRAM_SLUG = {
imba: 'imba',
mcsds: 'masters-in-computer-data-science'
};
const PATH = 'university-programs/';
const EPIC_OVERRIDES = {
UniversityProduct: {
enableQualification: [
'imba',
'masters-in-computer-data-science'
]
}
};
describe('[up]', function() {
it('MCS-DS landing page loads successfully', function() {
return browser
.startFresh()
.withEpicOverrides(EPIC_OVERRIDES)
.navigateTo(PATH + PROGRAM_SLUG.mcsds)
.assertElementExists(SELECTOR.programLandingPage)
// Check qualification forms load successfuly
.click(SELECTOR.requestInfoButton)
.assertElementExists(SELECTOR.surveySection);
});
it('iMBA landing page loads successfully', function() {
return browser
.startFresh()
.withEpicOverrides(EPIC_OVERRIDES)
.navigateTo(PATH + PROGRAM_SLUG.imba)
.assertElementExists(SELECTOR.programLandingPage)
// Check qualification forms load successfuly
.click(SELECTOR.requestInfoButton)
.assertElementExists(SELECTOR.surveySection);
});
});
"""
# chai-enzyme
'espec-checked':
'prefix': 'espec-checked'
'body': """
expect(wrapper.find('#checked')).to.be.checked();
"""
'espec-className':
'prefix': 'espec-className'
'body': """
expect(wrapper.find('span')).to.have.className('child');
"""
'espec-contain':
'prefix': 'espec-contain'
'body': """
// not for render
expect(wrapper).to.not.contain(<User index={3} />);
"""
'espec-descendants':
'prefix': 'espec-descendants'
'body': """
// including root element
expect(wrapper).to.have.descendants(User);
"""
'espec-exactly':
'prefix': 'espec-exactly'
'body': """
expect(wrapper).to.have.exactly(2).descendants('.item');
"""
'espec-disabled':
'prefix': 'espec-disabled'
'body': """
expect(wrapper.find('#disabled')).to.be.disabled();
"""
'espec-blank':
'prefix': 'espec-blank'
'body': """
expect(wrapper.find('#child')).to.be.blank();
"""
# alias to blank
'espec-empty':
'prefix': 'espec-empty'
'body': """
expect(wrapper.find('#child')).to.be.empty;
"""
'espec-present':
'prefix': 'espec-present'
'body': """
expect(wrapper.find('#parent')).be.present();
"""
# alias to present
'espec-exist':
'prefix': 'espec-exist'
'body': """
expect(wrapper.find('#parent')).to.exist; // an alias
"""
'espec-html':
'prefix': 'espec-html'
'body': """
expect(wrapper.find('#child')).to.have.html('<span id="child">Test</span>');
"""
'espec-id':
'prefix': 'espec-id'
'body': """
expect(wrapper).to.have.id('root');
"""
'espec-match':
'prefix': 'espec-match'
'body': """
expect(wrapper.find('span')).to.match('#child');
"""
'espec-ref':
'prefix': 'espec-ref'
'body': """
//render no
expect(wrapper).to.have.ref('test');
"""
# for select option
'espec-selected':
'prefix': 'espec-selected'
'body': """
expect(wrapper.find('#test1')).to.be.selected();
"""
'espec-tagName':
'prefix': 'espec-tagName'
'body': """
expect(wrapper).to.have.tagName('div');
"""
'espec-text-all':
'prefix': 'espec-text-all'
'body': """
expect(wrapper.find('#child')).to.have.text('Test');
expect(wrapper.find('#child')).to.contain.text('Te');
expect(wrapper.find('#child')).to.include.text('Te');
expect(wrapper.find('#child')).to.have.text().match(/Test/);
"""
'espec-value':
'prefix': 'espec-value'
'body': """
expect(wrapper.find('input')).to.have.value('test')
"""
'espec-id':
'prefix': 'espec-id'
'body': """
expect(wrapper.find('span')).to.have.attr('id');
expect(wrapper).to.have.attr('id', 'root');
expect(wrapper).to.have.attr('id').equal('root');
"""
'espec-data':
'prefix': 'espec-data'
'body': """
expect(wrapper).to.have.data('name')
expect(wrapper).to.have.data('name', 'root')
expect(wrapper).to.have.data('name').equal('root')
"""
'espec-style':
'prefix': 'espec-style'
'body': """
expect(wrapper).to.have.style('border')
expect(wrapper).to.have.style('border', '1px')
expect(wrapper).to.have.style('border').equal('1px')
"""
'espec-state':
'prefix': 'espec-state'
'body': """
//render no
expect(wrapper).to.have.state('foo')
expect(wrapper).to.have.state('foo', 'bar')
expect(wrapper).to.have.state('foo').equal('bar')
"""
'espec-prop':
'prefix': 'espec-prop'
'body': """
//render no
expect(wrapper.find(User).first()).to.have.prop('index')
expect(wrapper.find(User).first()).to.have.prop('index', 1)
expect(wrapper.find(User).first()).to.have.prop('user').deep.equal({name: 'Jane'})
"""
'espec-style':
'prefix': 'espec-style'
'body': """
"""
'enzyme.mount':
'prefix': "moun"
'body': "mount(<$1 />${2:, options}${3:, options.context}${4:, options.attachTo}${5:, options.childContextTypes});"
'mount.find':
'prefix': "find"
'body': "$1.find(${2:selector});"
'mount.findWhere':
'prefix': "findWhere"
'body': "$1.findWhere(${2:predicate});"
'mount.filter':
'prefix': "filter"
'body': "$1.filter(${2:selector});"
'mount.filterWhere':
'prefix': "filterWhere"
'body': "$1.filterWhere(${2:predicate})"
'mount.contains':
'prefix': "contains"
'body': "$1.contains(${2:nodeOrNodes})"
'mount.hasClass':
'prefix': "hasClass"
'body': "$1.hasClass(${2:className})"
'mount.is':
'prefix': "is"
'body': "$1.is(${2:selector})"
'mount.not':
'prefix': "not"
'body': "$1.not(${2:selector})"
'mount.children':
'prefix': "children"
'body': "$1.children()"
'mount.childAt':
'prefix': "childAt"
'body': "$1.childAt()"
'mount.parents':
'prefix': "parents"
'body': "$1.parents()"
'mount.parent':
'prefix': "parent"
'body': "$1.parent()"
'mount.closest':
'prefix': "closest"
'body': "$1.closest(${2:selector})"
'mount.render':
'prefix': "render"
'body': "$1.render()"
'mount.text':
'prefix': "text"
'body': "$1.text()"
'mount.html':
'prefix': "html"
'body': "$1.html()"
'mount.get':
'prefix': "get"
'body': "$1.get(${2:index})"
'mount.at':
'prefix': "at"
'body': "$1.at(${2:index})"
'mount.first':
'prefix': "first"
'body': "$1.first()"
'mount.last':
'prefix': "last"
'body': "$1.last()"
'mount.state':
'prefix': "state"
'body': "$1.state(${2:[key]})"
'mount.context':
'prefix': "context"
'body': "$1.context(${2:[key]})"
'mount.props':
'prefix': "props"
'body': "$1.props()"
'mount.prop':
'prefix': "prop"
'body': "$1.prop(${2:key})"
'mount.simulate':
'prefix': "simulate"
'body': "$1.simulate(${2:event}${3:, [data]})"
'mount.setState':
'prefix': "setState"
'body': "$1.setState(${2:nextState})"
'mount.setProps':
'prefix': "setProps"
'body': "$1.setProps(${2:nextProps})"
'mount.setContext':
'prefix': "setContext"
'body': "$1.setContext(${2:context})"
'mount.instance':
'prefix': "instance"
'body': "$1.instance()"
'mount.unmount':
'prefix': "unmount"
'body': "$1.unmount()"
'mount.mount':
'prefix': "mount"
'body': "$1.mount()"
'mount.update':
'prefix': "update"
'body': "$1.update()"
'mount.debug':
'prefix': "debug"
'body': "$1.debug()"
'mount.type':
'prefix': "type"
'body': "$1.type()"
'mount.forEach':
'prefix': "forEach"
'body': "$1.forEach(${2:fn})"
'mount.reduce':
'prefix': "reduce"
'body': "$1.reduce(${2:fn}${3:, [initialValue]})"
'mount.reduceRight':
'prefix': "reduceRight"
'body': "$1.reduceRight(${2:fn}${3:, [initialValue]})"
'mount.some':
'prefix': "some"
'body': "$1.some(${2:selector})"
'mount.someWhere':
'prefix': "someWhere"
'body': "$1.someWhere(${2:predicate})"
'mount.every':
'prefix': "every"
'body': "$1.every(${2:selector})"
'mount.everyWhere':
'prefix': "everyWhere"
'body': "$1.everyWhere(${2:predicate})"
'mount.ref':
'prefix': "ref"
'body': "$1.ref(${2:refName})"
'mount.detach':
'prefix': "detach"
'body': "$1.detach()"
'comment-Sep':
'prefix': 'comment-Sep'
'body': """
/** *************${1:Commnet}************* **/
"""
# /***************new ***********
'test-simple':
'prefix': 'test-simple'
'body': """
/* globals React */
const shallow = require('enzyme').shallow;
const expect = require('chai').expect;
const setup = require('static/bundles/test/componentSetup');
describe('${1:IconInfoBlock}', () => {
setup();
let wrapper;
let ${1:IconInfoBlock};
const propMock = {
iconName: 'stackSmall',
imgAlt: 'Icon',
infoText: 'abc'
};
before(() => {
${1:IconInfoBlock} = environment.require('bundles/program-home/components/${1:IconInfoBlock}');
wrapper = shallow(<${1:IconInfoBlock} {...propMock} />);
});
describe('UI render', () => {
it('should render IconWidget', () => {
expect(wrapper.find('rc-IconWidget')).to.have.length(1);
});
it('should render the infoText', () => {
expect(wrapper.find('span').text()).to.be.equal(propMock.infoText);
});
});
});
"""
'test-simple-stub':
'prefix': 'test-simple-stub'
'body': """
/* globals React */
const shallow = require('enzyme').shallow;
const expect = require('chai').expect;
const setup = require('static/bundles/test/componentSetup');
const sinon = require('sinon');
describe('${1:IconInfoBlock}', () => {
setup();
let wrapper;
let ${1:IconInfoBlock};
const propMock = {
handleClose: sinon.stub(),
handleUnenroll: sinon.stub()
};
before(() => {
${1:IconInfoBlock} = environment.require('bundles/program-home/components/${1:IconInfoBlock}');
wrapper = shallow(<${1:IconInfoBlock} {...propMock} />);
});
describe('UI render', () => {
it('should render', () => {
expect(true).to.equal(true);
});
});
describe('behaviors', () => {
it('should behave as expected', () => {
expect(true).to.equal(true);
});
});
});
"""
'espe-text':
'prefix': 'espe-text'
'body': """
expect(wrapper.find('${1:span}').text()).to.be.equal(${2:propMock}${3:.infoText});
"""
'esp-find-simulate':
'prefix': 'esp-find-simulate'
'body': """
wrapper.find('.${1:cancel-button}').simulate('click');
"""
'esp-called-once':
'prefix': 'esp-called-once'
'body': """
expect(${1:propMock.handleUnenroll}.calledOnce).to.equal(true);
"""
'SnippetName':
'prefix': 'SnippetName'
'body': """
Hello Wolrd
"""
'req-sinon':
'prefix': 'req-sinon'
'body': """
const sinon = require('sinon');
"""
'req-formatted-html-message':
'prefix': 'req-formatted-html-message'
'body': """
const {FormattedHTMLMessage} = require('js/lib/coursera.react-intl');
"""
'eslint-expression':
'prefix': 'eslint-expression'
'body': """
/* eslint-disable no-unused-expressions */
"""
'before':
'prefix': 'before'
'body': """
before(() => {
wrapper = shallow(<${1:S12nCourseCard} {...propMock} />${2:, {context}});
});
"""
'env-define':
'prefix': 'env-define'
'body': """
environment.define('bundles/${program-home}/actions/CourseActionCreators}', () => ({
${2:getCourse: () => Q()}
}));
"""
'beforeEach':
'prefix': 'beforeEach'
'body': """
beforeEach(() => {
wrapper = shallow(<${1:S12nCourseCard} {...propMock} />${2:, {context}});
});
"""
'rpt':
'prefix': 'rpt'
'body': """
React.PropTypes.${1:string}${2:.isRequired}
"""
'default-props':
'prefix': 'default-props'
'body': """
static defaultProps = {
${1:isEnrolled}: ${2:true}
}
"""
'mock-url':
'prefix': 'mock-url'
'body': """
'http://coursera.org/'
"""
'mock-url-image':
'prefix': 'mock-url-image'
'body': """
'http://coursera.org/mock-image.jpg'
"""
'mock-url-video':
'prefix': 'mock-ur-videol'
'body': """
'http://coursera.org/mock-video.mp4'
"""
'formattedHTMLMessage':
'prefix': 'formattedHTMLMessage'
'body': """
const {FormattedHTMLMessage} = require('js/lib/coursera.react-intl');
<FormattedHTMLMessage
message={_t(`
Questions? Check out the
<a href="{url}" target="_blank" rel="noopener noreferrer">Help Center</a>.
`)}
url={HELP_CENTER_LINK}
/>
"""
'QDefer':
'prefix': 'QDefer'
'body': """
const defer = Q.defer();
defer.resolve({data: 'fake data for unenroll', url: uri.toString()});
return defer.promise;
"""
'context-mock':
'prefix': 'context-mock'
'body': """
const contextMock = {
executeAction: () => {},
getStore: (storeName) => {
return {
getUserData: () => {
return {
id: 1
};
}
};
}
};
"""
'wp-instance':
'prefix': 'wp-instance'
'body': """
wrapper.instance().${1:handleClose}();
"""
'esp-equal':
'prefix': 'esp-equal'
'body': """
expect(${1:output}).to.equal(${2:true});
"""
'test-simple-action':
'prefix': 'test-simple-action'
'body': """
/* globals React */
const expect = require('chai').expect;
const setup = require('static/bundles/test/componentSetup');
const sinon = require('sinon');
describe('${1:ProgramHomeAlertActions}', () => {
setup();
let mockActionContext;
let actions;
describe('#${3:flushAlerts}', () => {
before(() => {
actions = environment.require('bundles/program-home/actions/${1:ProgramHomeAlertActions}');
mockActionContext = {
dispatch: sinon.spy()
};
});
it('should dispatch ${2:FLUSH_ALERTS} ', () => {
actions.${3:flushAlerts}(mockActionContext);
expect(mockActionContext.dispatch.calledWith(
'${2:FLUSH_ALERTS}'
)).to.equal(true);
});
});
});
"""
'SnippetName':
'prefix': 'SnippetName'
'body': """
Hello Wolrd
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment