├── examples ├── .gitignore ├── .babelrc ├── with-flow │ ├── .flowconfig │ ├── .babelrc │ ├── pages │ │ ├── index.js │ │ └── greeting.js │ ├── package.json │ └── routes.js ├── with-qs │ ├── package.json │ ├── routes.js │ └── pages │ │ └── index.js └── basic-with-express │ ├── pages │ ├── index.js │ └── greeting.js │ ├── package.json │ ├── routes.js │ └── server.js ├── .gitignore ├── .babelrc ├── flow-typed └── npm │ ├── flow-bin_v0.x.x.js │ ├── enzyme_v3.x.x.js │ ├── next_vx.x.x.js │ └── jest_v22.x.x.js ├── .flowconfig ├── .eslintrc ├── src ├── link.js ├── utils │ └── paramsToQueryString.js └── index.js ├── LICENSE ├── __tests__ ├── utils │ └── paramsToQueryString.spec.js ├── link.spec.js └── index.spec.js ├── package.json └── README.md /examples/.gitignore: -------------------------------------------------------------------------------- 1 | .next 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /examples/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["react"] 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | lib/ 4 | .idea 5 | -------------------------------------------------------------------------------- /examples/with-flow/.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | 3 | [include] 4 | 5 | [libs] 6 | 7 | [options] 8 | -------------------------------------------------------------------------------- /examples/with-flow/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "next/babel" 4 | ], 5 | "plugins": [ 6 | "transform-flow-strip-types" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["es2015", "react", "stage-2"], 3 | "plugins": [ 4 | ["module-resolver", {"alias": {"next-url-prettifier": "./src"}}], 5 | "transform-class-properties", 6 | "transform-flow-strip-types" 7 | ] 8 | } 9 | -------------------------------------------------------------------------------- /flow-typed/npm/flow-bin_v0.x.x.js: -------------------------------------------------------------------------------- 1 | // flow-typed signature: 6a5610678d4b01e13bbfbbc62bdaf583 2 | // flow-typed version: 3817bc6980/flow-bin_v0.x.x/flow_>=v0.25.x 3 | 4 | declare module "flow-bin" { 5 | declare module.exports: string; 6 | } 7 | -------------------------------------------------------------------------------- /.flowconfig: -------------------------------------------------------------------------------- 1 | [ignore] 2 | .*/examples/.* 3 | .*/config-chain/test/.* 4 | .*/npmconf/test/.* 5 | 6 | [include] 7 | 8 | [libs] 9 | flow-typed 10 | 11 | [options] 12 | suppress_comment= \\(.\\|\n\\)*\\$FlowIgnore 13 | module.name_mapper='^\next-url-prettifier/\(.*\)$' -> '/src/\1' 14 | -------------------------------------------------------------------------------- /examples/with-qs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "dev": "next", 4 | "build": "next build", 5 | "start": "next start" 6 | }, 7 | "dependencies": { 8 | "next": "*", 9 | "next-url-prettifier": "*", 10 | "qs": "*", 11 | "react": "*", 12 | "react-dom": "*" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /examples/with-qs/routes.js: -------------------------------------------------------------------------------- 1 | const UrlPrettifier = require('next-url-prettifier').default; 2 | const qs = require('qs'); 3 | 4 | const routes = []; 5 | 6 | const urlPrettifier = new UrlPrettifier(routes, { 7 | paramsToQueryString: (params) => `?${qs.stringify(params)}` 8 | }); 9 | exports.default = routes; 10 | exports.Router = urlPrettifier; 11 | -------------------------------------------------------------------------------- /examples/basic-with-express/pages/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | export default function IndexPage() { 4 | return ( 5 |
6 |

Homepage

7 |
8 | Name: 9 | 10 |
11 |
12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /examples/with-flow/pages/index.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import React from 'react'; 3 | 4 | export default function IndexPage() { 5 | return ( 6 |
7 |

Homepage

8 |
9 | Name: 10 | 11 |
12 |
13 | ); 14 | } 15 | -------------------------------------------------------------------------------- /examples/basic-with-express/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "dev": "node server.js", 4 | "build": "next build", 5 | "start": "NODE_ENV=production node server.js" 6 | }, 7 | "dependencies": { 8 | "express": "*", 9 | "next": "*", 10 | "next-url-prettifier": "*", 11 | "prop-types": "*", 12 | "react": "*", 13 | "react-dom": "*" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/with-flow/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "scripts": { 3 | "dev": "next", 4 | "build": "next build", 5 | "start": "next start", 6 | "flow": "flow" 7 | }, 8 | "dependencies": { 9 | "express": "*", 10 | "next": "*", 11 | "next-url-prettifier": "*", 12 | "react": "*", 13 | "react-dom": "*" 14 | }, 15 | "devDependencies": { 16 | "babel-plugin-transform-flow-strip-types": "*", 17 | "flow-bin": "*" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /examples/with-qs/pages/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {Link} from 'next-url-prettifier'; 3 | import {Router} from '../routes'; 4 | 5 | export default function IndexPage() { 6 | const linkParams = { 7 | a: 1, 8 | b: [2, 3], 9 | c: {d: [4, 5]} 10 | }; 11 | return ( 12 |
13 |

Homepage

14 | 15 | Link with complex params 16 | 17 |
18 | ); 19 | } 20 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { 4 | "es6": true, 5 | "browser": true, 6 | "node": true, 7 | "jest": true 8 | }, 9 | "extends": ["eslint:recommended", "plugin:react/recommended"], 10 | "parser": "babel-eslint", 11 | "parserOptions": { 12 | "ecmaVersion": 6, 13 | "ecmaFeatures": { 14 | "jsx": true 15 | } 16 | }, 17 | "plugins": [ 18 | "react", "flowtype" 19 | ], 20 | "settings": { 21 | "flowtype": { 22 | "onlyFilesWithFlowAnnotation": true 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /examples/basic-with-express/routes.js: -------------------------------------------------------------------------------- 1 | const UrlPrettifier = require('next-url-prettifier').default; 2 | 3 | const routes = [ 4 | { 5 | page: 'index', 6 | prettyUrl: '/home' 7 | }, 8 | { 9 | page: 'greeting', 10 | prettyUrl: ({lang = '', name = ''}) => 11 | (lang === 'fr' ? `/bonjour/${name}` : `/hello/${name}`), 12 | prettyUrlPatterns: [ 13 | {pattern: '/hello/:name', defaultParams: {lang: 'en'}}, 14 | {pattern: '/bonjour/:name', defaultParams: {lang: 'fr'}} 15 | ] 16 | } 17 | ]; 18 | 19 | const urlPrettifier = new UrlPrettifier(routes); 20 | exports.default = routes; 21 | exports.Router = urlPrettifier; 22 | -------------------------------------------------------------------------------- /examples/basic-with-express/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express'); 2 | const next = require('next'); 3 | const Router = require('./routes').Router; 4 | 5 | const dev = process.env.NODE_ENV !== 'production'; 6 | const port = parseInt(process.env.PORT, 10) || 3000; 7 | const app = next({dev}); 8 | const handle = app.getRequestHandler(); 9 | 10 | app.prepare() 11 | .then(() => { 12 | const server = express(); 13 | 14 | Router.forEachPrettyPattern((page, pattern, defaultParams) => server.get(pattern, (req, res) => 15 | app.render(req, res, `/${page}`, Object.assign({}, defaultParams, req.query, req.params)) 16 | )); 17 | 18 | server.get('*', (req, res) => handle(req, res)); 19 | server.listen(port); 20 | }) 21 | ; 22 | -------------------------------------------------------------------------------- /src/link.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import React from 'react'; 3 | import Link from 'next/link'; 4 | 5 | /* Types */ 6 | export type RouteLinkParamsType = { 7 | href?: string, 8 | as?: string 9 | }; 10 | 11 | type NextLinkPropsType = Object; // Next is not typed 12 | 13 | export type PropsType = { 14 | children?: any, 15 | route?: RouteLinkParamsType 16 | } & NextLinkPropsType; 17 | 18 | /* Component */ 19 | export default class PrettyLink extends React.Component { 20 | props: PropsType; 21 | 22 | render() { 23 | const {href, route, children, ...rest}: PropsType = this.props; 24 | return href || (route && route.href) 25 | ? 26 | : children 27 | ? children 28 | : null 29 | ; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /examples/with-flow/routes.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import UrlPrettifier from 'next-url-prettifier'; 3 | import type {RouteType} from 'next-url-prettifier'; 4 | 5 | export type PageNameType = 'index' | 'greeting'; 6 | 7 | const routes: RouteType[] = [ 8 | { 9 | page: 'greeting', 10 | prettyUrl: ({lang = '', name = ''}: {lang: string, name: string}): string => 11 | (lang === 'fr' ? `/bonjour/${name}` : `/hello/${name}`), 12 | prettyUrlPatterns: [ 13 | {pattern: '/hello/:name', defaultParams: {lang: 'en'}}, 14 | {pattern: '/bonjour/:name', defaultParams: {lang: 'fr'}} 15 | ] 16 | } 17 | ]; 18 | 19 | const urlPrettifier: UrlPrettifier = new UrlPrettifier(routes); 20 | export default routes; 21 | export {urlPrettifier as Router}; 22 | export type {RouteType}; 23 | -------------------------------------------------------------------------------- /examples/basic-with-express/pages/greeting.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {Link} from 'next-url-prettifier'; 3 | import PropTypes from 'prop-types'; 4 | import {Router} from '../routes'; 5 | 6 | export default class GreetingPage extends React.Component { 7 | static getInitialProps({query: {lang, name}}) { 8 | return {lang, name}; 9 | } 10 | 11 | renderSwitchLangageLink() { 12 | const {lang, name} = this.props; 13 | const switchLang = lang === 'fr' ? 'en' : 'fr'; 14 | return ( 15 | 16 | {switchLang === 'fr' ? 'Français' : 'English'} 17 | 18 | ); 19 | } 20 | 21 | render() { 22 | const {lang, name} = this.props; 23 | return ( 24 |
25 |

{lang === 'fr' ? 'Bonjour' : 'Hello'} {name}

26 |
{this.renderSwitchLangageLink()}
27 |
28 | ); 29 | } 30 | } 31 | 32 | GreetingPage.propTypes = { 33 | lang: PropTypes.string, 34 | name: PropTypes.string 35 | }; 36 | -------------------------------------------------------------------------------- /src/utils/paramsToQueryString.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | 3 | const isObject: (any) => boolean = (param: any): boolean => 4 | param === Object(param) 5 | ; 6 | 7 | const paramsToStringList = (entries: [string, any][]): string[] => 8 | entries.reduce( 9 | (result: string[], [key, value]: [string, any]): string[] => 10 | result.concat(Array.isArray(value) 11 | ? paramsToStringList( 12 | value.map((arrayValue: any): [string, any] => [`${key}[]`, arrayValue]) 13 | ) 14 | : [typeof value === 'string' || typeof value === 'number' ? `${key}=${value}` : '']), 15 | [] 16 | ) 17 | ; 18 | 19 | export default function paramsToQueryString(params: any): string { 20 | const paramsString: string = isObject(params) 21 | ? paramsToStringList( 22 | Object.keys(params) 23 | .sort() 24 | .map((key: string | number): [string, any] => [String(key), params[key]]) 25 | ) 26 | .filter((chunk: string): boolean => chunk.length > 0) 27 | .join('&') 28 | : '' 29 | ; 30 | return paramsString.length > 0 ? `?${paramsString}` : ''; 31 | } 32 | -------------------------------------------------------------------------------- /examples/with-flow/pages/greeting.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import React from 'react'; 3 | import {Link} from 'next-url-prettifier'; 4 | import {Router} from '../routes'; 5 | 6 | type PropsType = { 7 | lang: ?('en' | 'fr'), 8 | name: ?string 9 | }; 10 | 11 | export default class GreetingPage extends React.Component { 12 | props: PropsType; 13 | 14 | static getInitialProps({query: {lang, name}}: {query: PropsType}): PropsType { 15 | return {lang, name}; 16 | } 17 | 18 | renderSwitchLangageLink() { 19 | const {lang, name}: PropsType = this.props; 20 | const switchLang: string = lang === 'fr' ? 'en' : 'fr'; 21 | return ( 22 | 23 | {switchLang === 'fr' ? 'Français' : 'English'} 24 | 25 | ); 26 | } 27 | 28 | render() { 29 | const {lang, name}: PropsType = this.props; 30 | return ( 31 |
32 |

{lang === 'fr' ? 'Bonjour' : 'Hello'} {name}

33 |
{this.renderSwitchLangageLink()}
34 |
35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 BDav24 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /__tests__/utils/paramsToQueryString.spec.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import paramsToQueryString from 'next-url-prettifier/utils/paramsToQueryString'; 3 | 4 | describe('paramsToQueryString', (): void => { 5 | it('returns ordered query string', (): void => { 6 | expect(paramsToQueryString({ 7 | foo: 'bar', 8 | bar: 0, 9 | baz: 1 10 | })).toBe('?bar=0&baz=1&foo=bar'); 11 | }); 12 | 13 | it('should not display null, undefined params or unknow types in query string', (): void => { 14 | expect(paramsToQueryString({ 15 | nullValues: null, 16 | undefinedValues: undefined 17 | })).toBe(''); 18 | expect(paramsToQueryString({ 19 | nullValues: null, 20 | undefinedValues: undefined, 21 | foo: 'bar', 22 | bar: ['one', {two: 2}] 23 | })).toBe('?bar[]=one&foo=bar'); 24 | }); 25 | 26 | it('should represent arrays with brackets', (): void => { 27 | expect(paramsToQueryString({ 28 | bar: ['one', 'two', ['three']] 29 | })).toBe('?bar[]=one&bar[]=two&bar[][]=three'); 30 | }); 31 | 32 | it('should not display empty arrays in query string', (): void => { 33 | expect(paramsToQueryString({ 34 | foo: 'bar', 35 | empty: [] 36 | })).toBe('?foo=bar'); 37 | }); 38 | 39 | it('returns an empty string if params is not an object', (): void => { 40 | expect(paramsToQueryString()).toBe(''); 41 | expect(paramsToQueryString(0)).toBe(''); 42 | expect(paramsToQueryString('')).toBe(''); 43 | expect(paramsToQueryString([])).toBe(''); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /__tests__/link.spec.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import React from 'react'; 3 | import {configure, shallow, ShallowWrapper} from 'enzyme'; 4 | import Adapter from 'enzyme-adapter-react-16' 5 | import NextLink from 'next/link'; 6 | // Local 7 | import PrettyLink from 'next-url-prettifier/link'; 8 | // Types 9 | import type {RouteLinkParamsType} from 'next-url-prettifier/link'; 10 | 11 | configure({adapter: new Adapter()}) 12 | 13 | describe('PrettyLink', (): void => { 14 | it('should behave like next/link if route is not specified', (): void => { 15 | const a = label; 16 | expect(shallow({a}).html()) 17 | .toBe(shallow({a}).html()); 18 | }); 19 | 20 | it('should add href and as if route is specified', (): void => { 21 | const a = label; 22 | const routeParams: RouteLinkParamsType = { 23 | href: '/pageName?id=1', 24 | as: '/page-pretty-url-1' 25 | }; 26 | const link: ShallowWrapper 27 | = shallow({a}); 28 | const nextLink: ShallowWrapper 29 | = shallow({a}); 30 | 31 | expect(link.name()).toBe('Link'); 32 | expect(link.prop('href')).toBe('/pageName?id=1'); 33 | expect(link.prop('as')).toBe('/page-pretty-url-1'); 34 | expect(link.html()).toBe(nextLink.html()); 35 | }); 36 | 37 | it('should only render children if no href is provided', (): void => { 38 | const a = label; 39 | expect(shallow({a}).html()) 40 | .toEqual(shallow(a).html()); 41 | }); 42 | }); 43 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "next-url-prettifier", 3 | "version": "1.4.0", 4 | "description": "Url prettifier for Next Framework", 5 | "main": "lib/index.js", 6 | "files": [ 7 | "lib" 8 | ], 9 | "repository": "https://github.com/BDav24/next-url-prettifier.git", 10 | "author": "BDav24", 11 | "license": "MIT", 12 | "keywords": [ 13 | "next", 14 | "next.js", 15 | "nextjs", 16 | "pretty-url", 17 | "react", 18 | "route", 19 | "routes", 20 | "router" 21 | ], 22 | "scripts": { 23 | "build": "babel src --out-dir lib && yarn run build-dot-flow", 24 | "build-dot-flow": "find ./src -name '*.js' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/lib\\//g'`.flow; done", 25 | "lint": "eslint --ignore-pattern 'flow-typed' --ignore-pattern 'lib' .", 26 | "prepublish": "yarn run build", 27 | "qa": "yarn run flow && yarn run test", 28 | "test": "jest --coverage" 29 | }, 30 | "peerDependencies": { 31 | "next": ">= 1", 32 | "react": ">= 15" 33 | }, 34 | "devDependencies": { 35 | "babel-cli": "^6.26.0", 36 | "babel-eslint": "^10.0.1", 37 | "babel-plugin-module-resolver": "^3.1.1", 38 | "babel-plugin-transform-class-properties": "^6.24.1", 39 | "babel-plugin-transform-flow-strip-types": "^6.22.0", 40 | "babel-preset-es2015": "^6.24.1", 41 | "babel-preset-react": "^6.24.1", 42 | "babel-preset-stage-2": "^6.24.1", 43 | "enzyme": "^3.7.0", 44 | "enzyme-adapter-react-16": "^1.6.0", 45 | "eslint": "^5.7.0", 46 | "eslint-config-airbnb": "^17.1.0", 47 | "eslint-plugin-flowtype": "^3.0.0", 48 | "eslint-plugin-react": "^7.11.1", 49 | "flow-bin": "^0.83.0", 50 | "flow-typed": "^2.5.1", 51 | "jest": "^23.6.0", 52 | "next": "^7.0.2", 53 | "react": "^16.5.2", 54 | "react-addons-test-utils": "^15.6.2", 55 | "react-dom": "^16.5.2" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import defaultParamsToQueryString from './utils/paramsToQueryString'; 3 | import Link from './link'; 4 | // Types 5 | import type {RouteLinkParamsType} from './link'; 6 | 7 | /* Types */ 8 | export type ParamType = any; 9 | export type PatternType = string; 10 | export type PrettyPatternType = {pattern: PatternType, defaultParams?: ParamType}; 11 | 12 | export type RouteType = { 13 | page: PageNameType, 14 | prettyUrl?: string | (params: ParamType) => string, 15 | prettyPatterns?: PatternType | (PatternType | PrettyPatternType)[], 16 | prettyUrlPatterns?: PatternType | (PatternType | PrettyPatternType)[] 17 | }; 18 | 19 | export type PatternFunctionType = 20 | (page: PageNameType, pattern: PatternType, defaultParams: ParamType) => any; 21 | 22 | export type UrlPrettifierOptionsType = { 23 | paramsToQueryString?: (ParamType) => string 24 | }; 25 | 26 | /* Component */ 27 | export default class UrlPrettifier { 28 | routes: RouteType[]; 29 | paramsToQueryString: (ParamType) => string; 30 | 31 | constructor(routes: RouteType[], options: UrlPrettifierOptionsType = {}): void { 32 | this.routes = routes; 33 | this.paramsToQueryString = options && options.paramsToQueryString 34 | ? options.paramsToQueryString 35 | : defaultParamsToQueryString 36 | ; 37 | } 38 | 39 | getPrettyUrl(pageName: T, params: ParamType): RouteLinkParamsType { 40 | const route: ?RouteType = this.routes.filter((currentRoute: RouteType): boolean => 41 | currentRoute.page === pageName)[0]; 42 | return { 43 | href: `/${pageName}${this.paramsToQueryString(params)}`, 44 | ...(route && route.prettyUrl 45 | ? {as: typeof route.prettyUrl === 'string' ? route.prettyUrl : route.prettyUrl(params)} 46 | : {} 47 | ) 48 | }; 49 | } 50 | 51 | linkPage(pageName: T, params: ParamType): RouteLinkParamsType { 52 | // eslint-disable-next-line no-console 53 | console.warn("linkPage() is deprecated. Use getPrettyUrl() instead."); 54 | return this.getPrettyUrl(pageName, params); 55 | } 56 | 57 | getPrettyUrlPatterns(route: RouteType): PrettyPatternType[] { 58 | return typeof route.prettyUrlPatterns === 'string' 59 | ? [{pattern: route.prettyUrlPatterns}] 60 | : Array.isArray(route.prettyUrlPatterns) 61 | ? route.prettyUrlPatterns.map( 62 | (pattern: PatternType | PrettyPatternType): PrettyPatternType => 63 | (typeof pattern === 'string' ? {pattern} : pattern) 64 | ) 65 | : typeof route.prettyUrl === 'string' 66 | ? [{pattern: route.prettyUrl}] 67 | : [] 68 | ; 69 | } 70 | 71 | getPrettyPatterns(route: RouteType): PrettyPatternType[] { 72 | return typeof route.prettyPatterns === 'string' 73 | ? [{pattern: route.prettyPatterns}] 74 | : Array.isArray(route.prettyPatterns) 75 | ? route.prettyPatterns.map( 76 | (pattern: PatternType | PrettyPatternType): PrettyPatternType => 77 | (typeof pattern === 'string' ? {pattern} : pattern) 78 | ) 79 | : typeof route.prettyUrl === 'string' 80 | ? [{pattern: route.prettyUrl}] 81 | : [] 82 | ; 83 | } 84 | 85 | forEachPrettyPattern(apply: PatternFunctionType): void { 86 | this.routes.forEach((route: RouteType): void => { 87 | this.getPrettyUrlPatterns(route).forEach((pattern: PrettyPatternType): any => 88 | apply(route.page, pattern.pattern, pattern.defaultParams) 89 | ); 90 | this.getPrettyPatterns(route).forEach((pattern: PrettyPatternType): any => 91 | apply(route.page, pattern.pattern, pattern.defaultParams) 92 | ); 93 | }); 94 | } 95 | 96 | forEachPattern(apply: PatternFunctionType): void { 97 | // eslint-disable-next-line no-console 98 | console.warn("forEachPattern() is deprecated. Use forEachPrettyPattern() instead."); 99 | this.forEachPrettyPattern(apply); 100 | } 101 | } 102 | 103 | export {Link as Link}; 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Url prettifier for Next Framework 2 | 3 | [![npm version](https://img.shields.io/npm/v/next-url-prettifier.svg?style=flat)](https://www.npmjs.com/package/next-url-prettifier) 4 | 5 | Easy to use url prettifier for [next.js](https://github.com/zeit/next.js). 6 | 7 | ## Why you should use it 8 | - Good integration with Next.js (only adds "href" and "as" props to existing Link) 9 | - On server-side, use the parameter matching you want (Express.js or else) 10 | - Handles reverse routing 11 | - It's flow typed and well tested 12 | - It's extendable (you can use the query stringfier you want) 13 | - No dependencies 14 | 15 | ## How to use 16 | 17 | #### Install: 18 | ```bash 19 | npm i --save next-url-prettifier 20 | ``` 21 | 22 | #### Create `routes.js` inside your project root: 23 | ```javascript 24 | // routes.js 25 | const UrlPrettifier = require('next-url-prettifier').default; 26 | 27 | const routes = [ 28 | { 29 | page: 'index', 30 | prettyUrl: '/home' 31 | }, 32 | { 33 | page: 'greeting', 34 | // `prettyUrl` is used on client side to construct the URL of your link 35 | prettyUrl: ({lang = '', name = ''}) => 36 | (lang === 'fr' ? `/bonjour/${name}` : `/hello/${name}`), 37 | // `prettyPatterns` is used on server side to find which component/page to display 38 | prettyPatterns: [ 39 | {pattern: '/hello/:name', defaultParams: {lang: 'en'}}, 40 | {pattern: '/bonjour/:name', defaultParams: {lang: 'fr'}} 41 | ] 42 | } 43 | ]; 44 | 45 | const urlPrettifier = new UrlPrettifier(routes); 46 | exports.default = routes; 47 | exports.Router = urlPrettifier; 48 | ``` 49 | 50 | #### In your components: 51 | ```javascript 52 | // pages/greeting.js 53 | import React from 'react'; 54 | import PropTypes from 'prop-types'; 55 | import {Link} from 'next-url-prettifier'; 56 | import {Router} from '../routes'; 57 | 58 | export default class GreetingPage extends React.Component { 59 | static getInitialProps({query: {lang, name}}) { 60 | return {lang, name}; 61 | } 62 | 63 | renderSwitchLangageLink() { 64 | const {lang, name} = this.props; 65 | const switchLang = lang === 'fr' ? 'en' : 'fr'; 66 | return ( 67 | 68 | {switchLang === 'fr' ? 'Français' : 'English'} 69 | 70 | ); 71 | /* 72 | Note: you can also use Next native Link and spread notation: 73 | import Link from 'next/link'; 74 | return ( 75 | 76 | {switchLang === 'fr' ? 'Français' : 'English'} 77 | 78 | ); 79 | */ 80 | } 81 | 82 | render() { 83 | const {lang, name} = this.props; 84 | return ( 85 |
86 |

{lang === 'fr' ? 'Bonjour' : 'Hello'} {name}

87 |
{this.renderSwitchLangageLink()}
88 |
89 | ); 90 | } 91 | } 92 | 93 | GreetingPage.propTypes = { 94 | lang: PropTypes.string, 95 | name: PropTypes.string 96 | }; 97 | ``` 98 | 99 | #### In your `server.js` file (example with Express.js): 100 | ```javascript 101 | // server.js 102 | const express = require('express'); 103 | const next = require('next'); 104 | const Router = require('./routes').Router; 105 | 106 | const dev = process.env.NODE_ENV !== 'production'; 107 | const port = parseInt(process.env.PORT, 10) || 3000; 108 | const app = next({dev}); 109 | const handle = app.getRequestHandler(); 110 | 111 | app.prepare() 112 | .then(() => { 113 | const server = express(); 114 | 115 | Router.forEachPrettyPattern((page, pattern, defaultParams) => server.get(pattern, (req, res) => 116 | app.render(req, res, `/${page}`, Object.assign({}, defaultParams, req.query, req.params)) 117 | )); 118 | 119 | server.get('*', (req, res) => handle(req, res)); 120 | server.listen(port); 121 | }) 122 | ; 123 | ``` 124 | 125 | ## Examples: 126 | - [Basic with Express](./examples/basic-with-express) 127 | - [With Flowtype](./examples/with-flow) 128 | - [With qs as query stringifier](./examples/with-qs) 129 | -------------------------------------------------------------------------------- /flow-typed/npm/enzyme_v3.x.x.js: -------------------------------------------------------------------------------- 1 | // flow-typed signature: 02db3523747059d89e87d4dec6873edf 2 | // flow-typed version: 62a0c60689/enzyme_v3.x.x/flow_>=v0.53.x 3 | 4 | import * as React from "react"; 5 | 6 | declare module "enzyme" { 7 | declare type PredicateFunction = ( 8 | wrapper: T, 9 | index: number 10 | ) => boolean; 11 | declare type NodeOrNodes = React.Node | Array; 12 | declare type EnzymeSelector = string | Class> | Object; 13 | 14 | // CheerioWrapper is a type alias for an actual cheerio instance 15 | // TODO: Reference correct type from cheerio's type declarations 16 | declare type CheerioWrapper = any; 17 | 18 | declare class Wrapper { 19 | find(selector: EnzymeSelector): this, 20 | findWhere(predicate: PredicateFunction): this, 21 | filter(selector: EnzymeSelector): this, 22 | filterWhere(predicate: PredicateFunction): this, 23 | hostNodes(): this, 24 | contains(nodeOrNodes: NodeOrNodes): boolean, 25 | containsMatchingElement(node: React.Node): boolean, 26 | containsAllMatchingElements(nodes: NodeOrNodes): boolean, 27 | containsAnyMatchingElements(nodes: NodeOrNodes): boolean, 28 | dive(option?: { context?: Object }): this, 29 | exists(): boolean, 30 | isEmptyRender(): boolean, 31 | matchesElement(node: React.Node): boolean, 32 | hasClass(className: string): boolean, 33 | is(selector: EnzymeSelector): boolean, 34 | isEmpty(): boolean, 35 | not(selector: EnzymeSelector): this, 36 | children(selector?: EnzymeSelector): this, 37 | childAt(index: number): this, 38 | parents(selector?: EnzymeSelector): this, 39 | parent(): this, 40 | closest(selector: EnzymeSelector): this, 41 | render(): CheerioWrapper, 42 | unmount(): this, 43 | text(): string, 44 | html(): string, 45 | get(index: number): React.Node, 46 | getNodes(): Array, 47 | getDOMNode(): HTMLElement | HTMLInputElement, 48 | at(index: number): this, 49 | first(): this, 50 | last(): this, 51 | state(key?: string): any, 52 | context(key?: string): any, 53 | props(): Object, 54 | prop(key: string): any, 55 | key(): string, 56 | simulate(event: string, ...args: Array): this, 57 | setState(state: {}, callback?: Function): this, 58 | setProps(props: {}): this, 59 | setContext(context: Object): this, 60 | instance(): React.Component<*, *>, 61 | update(): this, 62 | debug(): string, 63 | type(): string | Function | null, 64 | name(): string, 65 | forEach(fn: (node: this, index: number) => mixed): this, 66 | map(fn: (node: this, index: number) => T): Array, 67 | reduce( 68 | fn: (value: T, node: this, index: number) => T, 69 | initialValue?: T 70 | ): Array, 71 | reduceRight( 72 | fn: (value: T, node: this, index: number) => T, 73 | initialValue?: T 74 | ): Array, 75 | some(selector: EnzymeSelector): boolean, 76 | someWhere(predicate: PredicateFunction): boolean, 77 | every(selector: EnzymeSelector): boolean, 78 | everyWhere(predicate: PredicateFunction): boolean, 79 | length: number 80 | } 81 | 82 | declare class ReactWrapper extends Wrapper { 83 | constructor(nodes: NodeOrNodes, root: any, options?: ?Object): ReactWrapper, 84 | mount(): this, 85 | ref(refName: string): this, 86 | detach(): void 87 | } 88 | 89 | declare class ShallowWrapper extends Wrapper { 90 | constructor( 91 | nodes: NodeOrNodes, 92 | root: any, 93 | options?: ?Object 94 | ): ShallowWrapper, 95 | equals(node: React.Node): boolean, 96 | shallow(options?: { context?: Object }): ShallowWrapper 97 | } 98 | 99 | declare function shallow( 100 | node: React.Node, 101 | options?: { context?: Object, disableLifecycleMethods?: boolean } 102 | ): ShallowWrapper; 103 | declare function mount( 104 | node: React.Node, 105 | options?: { 106 | context?: Object, 107 | attachTo?: HTMLElement, 108 | childContextTypes?: Object 109 | } 110 | ): ReactWrapper; 111 | declare function render( 112 | node: React.Node, 113 | options?: { context?: Object } 114 | ): CheerioWrapper; 115 | 116 | declare module.exports: { 117 | configure(options: { 118 | Adapter?: any, 119 | disableLifecycleMethods?: boolean 120 | }): void, 121 | render: typeof render, 122 | mount: typeof mount, 123 | shallow: typeof shallow, 124 | ShallowWrapper: typeof ShallowWrapper, 125 | ReactWrapper: typeof ReactWrapper 126 | }; 127 | } 128 | -------------------------------------------------------------------------------- /__tests__/index.spec.js: -------------------------------------------------------------------------------- 1 | /* @flow */ 2 | import UrlPrettifier from 'next-url-prettifier/index'; 3 | // Types 4 | import type {RouteType, PrettyPatternType} from 'next-url-prettifier/index'; 5 | 6 | const patternString: string = '/page-pretty-url-:id'; 7 | const prettyPatterns: (PrettyPatternType | string)[] = [ 8 | {pattern: patternString}, 9 | {pattern: '/page-pretty-url-one', defaultParams: {id: 1}} 10 | ]; 11 | // prettyUrlPatterns is Deprecated 12 | const prettyUrlPatterns: (PrettyPatternType | string)[] = [ 13 | {pattern: patternString}, 14 | {pattern: '/page-pretty-url-one', defaultParams: {id: 1}} 15 | ]; 16 | const route: RouteType<*> = { 17 | page: 'pageName', 18 | prettyUrl: ({id}: {id: number}): string => `/page-pretty-url-${id}`, 19 | prettyPatterns 20 | }; 21 | const router: UrlPrettifier<*> = new UrlPrettifier([route]); 22 | 23 | describe('UrlPrettifier options', (): void => { 24 | it('should use paramsToQueryString if given', (): void => { 25 | const routerWithCustomQs: UrlPrettifier<*> = new UrlPrettifier([route], { 26 | paramsToQueryString: ({id}: {id: number}): string => `/id/${id}` 27 | }); 28 | expect(routerWithCustomQs.linkPage('pageName', {id: 1})) 29 | .toEqual({href: '/pageName/id/1', as: '/page-pretty-url-1'}); 30 | expect(routerWithCustomQs.getPrettyUrl('pageName', {id: 1})) 31 | .toEqual({href: '/pageName/id/1', as: '/page-pretty-url-1'}); 32 | }); 33 | }); 34 | 35 | describe('UrlPrettifier getPrettyUrl', (): void => { 36 | it('should return href and as for the route if prettyUrl is a function', (): void => { 37 | expect(router.getPrettyUrl('pageName', {id: 1})) 38 | .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'}); 39 | }); 40 | 41 | it('should return href and as for the route if prettyUrl is a string', (): void => { 42 | const routerWithString: UrlPrettifier<*> = new UrlPrettifier([ 43 | {...route, prettyUrl: '/page-pretty-url-1'} 44 | ]); 45 | expect(routerWithString.getPrettyUrl('pageName', {id: 1})) 46 | .toEqual({href: '/pageName?id=1', as: '/page-pretty-url-1'}); 47 | }); 48 | 49 | it('should return only href if the route does not exist', (): void => { 50 | expect(router.getPrettyUrl('unknownPage', {id: 1})) 51 | .toEqual({href: '/unknownPage?id=1'}); 52 | }); 53 | }); 54 | 55 | describe('UrlPrettifier getPrettyUrlPatterns (DEPRECATED)', (): void => { 56 | it('should return an empty list if prettyUrlPattern type is not allowed (DEPRECATED)', (): void => { 57 | // $FlowIgnore 58 | expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: {patternString}})) 59 | .toEqual([]); 60 | }); 61 | 62 | it('should return prettyUrl if its type is string and prettyUrlPattern is undefined (DEPRECATED)', (): void => { 63 | // eslint-disable-next-line no-unused-vars 64 | const {prettyUrlPatterns, ...routeWithoutPatterns}: RouteType<*> = route; 65 | expect(router.getPrettyUrlPatterns({...routeWithoutPatterns, prettyUrl: '/page-pretty-url-1'})) 66 | .toEqual([{pattern: '/page-pretty-url-1'}]); 67 | }); 68 | 69 | it('should return a PrettyPatternType if prettyUrlPattern is a string (DEPRECATED)', (): void => { 70 | expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: patternString})) 71 | .toEqual([{pattern: patternString}]); 72 | }); 73 | 74 | it('should return a PrettyPatternType if prettyUrlPattern is an array of string (DEPRECATED)', (): void => { 75 | expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns: [patternString]})) 76 | .toEqual([{pattern: patternString}]); 77 | }); 78 | 79 | it('should return a PrettyPatternType if prettyUrlPattern is rightly typed (DEPRECATED)', (): void => { 80 | expect(router.getPrettyUrlPatterns({...route, prettyUrlPatterns})) 81 | .toEqual(prettyUrlPatterns); 82 | }); 83 | }); 84 | 85 | describe('UrlPrettifier getPrettyPatterns', (): void => { 86 | it('should return an empty list if prettyPattern type is not allowed', (): void => { 87 | // $FlowIgnore 88 | expect(router.getPrettyPatterns({...route, prettyPatterns: {patternString}})) 89 | .toEqual([]); 90 | }); 91 | 92 | it('should return prettyUrl if its type is string and prettyPattern is undefined', (): void => { 93 | // eslint-disable-next-line no-unused-vars 94 | const {prettyPatterns, ...routeWithoutPatterns}: RouteType<*> = route; 95 | expect(router.getPrettyPatterns({...routeWithoutPatterns, prettyUrl: '/page-pretty-url-1'})) 96 | .toEqual([{pattern: '/page-pretty-url-1'}]); 97 | }); 98 | 99 | it('should return a PrettyPatternType if prettyPattern is a string', (): void => { 100 | expect(router.getPrettyPatterns({...route, prettyPatterns: patternString})) 101 | .toEqual([{pattern: patternString}]); 102 | }); 103 | 104 | it('should return a PrettyPatternType if prettyPattern is an array of string', (): void => { 105 | expect(router.getPrettyPatterns({...route, prettyPatterns: [patternString]})) 106 | .toEqual([{pattern: patternString}]); 107 | }); 108 | 109 | it('should return a PrettyPatternType if prettyPattern is rightly typed', (): void => { 110 | expect(router.getPrettyPatterns({...route, prettyPatterns})) 111 | .toEqual(prettyPatterns); 112 | }); 113 | }); 114 | 115 | describe('Router forEachPattern (DEPRECATED)', (): void => { 116 | it('should iterate on each pattern', (): void => { 117 | const router = new UrlPrettifier([{ 118 | page: 'pageName', 119 | prettyUrl: ({id}: {id: number}): string => `/page-pretty-url-${id}`, 120 | prettyUrlPatterns 121 | }]) 122 | const mockFunction = jest.fn(); 123 | router.forEachPattern(mockFunction); 124 | expect(mockFunction.mock.calls.length).toBe(2); 125 | expect(mockFunction).toHaveBeenCalledWith(route.page, patternString, undefined); 126 | expect(mockFunction).toHaveBeenCalledWith(route.page, '/page-pretty-url-one', {id: 1}); 127 | }); 128 | }); 129 | 130 | describe('Router forEachPrettyPattern', (): void => { 131 | it('should iterate on each pattern', (): void => { 132 | const mockFunction = jest.fn(); 133 | router.forEachPrettyPattern(mockFunction); 134 | expect(mockFunction.mock.calls.length).toBe(2); 135 | expect(mockFunction).toHaveBeenCalledWith(route.page, patternString, undefined); 136 | expect(mockFunction).toHaveBeenCalledWith(route.page, '/page-pretty-url-one', {id: 1}); 137 | }); 138 | }); 139 | -------------------------------------------------------------------------------- /flow-typed/npm/next_vx.x.x.js: -------------------------------------------------------------------------------- 1 | // flow-typed signature: 3adf18bcf6fb0f7ed085781b65e827dc 2 | // flow-typed version: <>/next_v^4.2.3/flow_v0.64.0 3 | 4 | /** 5 | * This is an autogenerated libdef stub for: 6 | * 7 | * 'next' 8 | * 9 | * Fill this stub out by replacing all the `any` types. 10 | * 11 | * Once filled out, we encourage you to share your work with the 12 | * community by sending a pull request to: 13 | * https://github.com/flowtype/flow-typed 14 | */ 15 | 16 | declare module 'next' { 17 | declare module.exports: any; 18 | } 19 | 20 | /** 21 | * We include stubs for each file inside this npm package in case you need to 22 | * require those files directly. Feel free to delete any files that aren't 23 | * needed. 24 | */ 25 | declare module 'next/babel' { 26 | declare module.exports: any; 27 | } 28 | 29 | declare module 'next/client' { 30 | declare module.exports: any; 31 | } 32 | 33 | declare module 'next/css' { 34 | declare module.exports: any; 35 | } 36 | 37 | declare module 'next/dist/client/head-manager' { 38 | declare module.exports: any; 39 | } 40 | 41 | declare module 'next/dist/client/index' { 42 | declare module.exports: any; 43 | } 44 | 45 | declare module 'next/dist/client/next-dev' { 46 | declare module.exports: any; 47 | } 48 | 49 | declare module 'next/dist/client/next' { 50 | declare module.exports: any; 51 | } 52 | 53 | declare module 'next/dist/client/on-demand-entries-client' { 54 | declare module.exports: any; 55 | } 56 | 57 | declare module 'next/dist/client/webpack-hot-middleware-client' { 58 | declare module.exports: any; 59 | } 60 | 61 | declare module 'next/dist/lib/app' { 62 | declare module.exports: any; 63 | } 64 | 65 | declare module 'next/dist/lib/css' { 66 | declare module.exports: any; 67 | } 68 | 69 | declare module 'next/dist/lib/dynamic' { 70 | declare module.exports: any; 71 | } 72 | 73 | declare module 'next/dist/lib/error-debug' { 74 | declare module.exports: any; 75 | } 76 | 77 | declare module 'next/dist/lib/error' { 78 | declare module.exports: any; 79 | } 80 | 81 | declare module 'next/dist/lib/EventEmitter' { 82 | declare module.exports: any; 83 | } 84 | 85 | declare module 'next/dist/lib/head' { 86 | declare module.exports: any; 87 | } 88 | 89 | declare module 'next/dist/lib/link' { 90 | declare module.exports: any; 91 | } 92 | 93 | declare module 'next/dist/lib/p-queue' { 94 | declare module.exports: any; 95 | } 96 | 97 | declare module 'next/dist/lib/page-loader' { 98 | declare module.exports: any; 99 | } 100 | 101 | declare module 'next/dist/lib/prefetch' { 102 | declare module.exports: any; 103 | } 104 | 105 | declare module 'next/dist/lib/router/index' { 106 | declare module.exports: any; 107 | } 108 | 109 | declare module 'next/dist/lib/router/router' { 110 | declare module.exports: any; 111 | } 112 | 113 | declare module 'next/dist/lib/router/with-router' { 114 | declare module.exports: any; 115 | } 116 | 117 | declare module 'next/dist/lib/shallow-equals' { 118 | declare module.exports: any; 119 | } 120 | 121 | declare module 'next/dist/lib/side-effect' { 122 | declare module.exports: any; 123 | } 124 | 125 | declare module 'next/dist/lib/utils' { 126 | declare module.exports: any; 127 | } 128 | 129 | declare module 'next/dist/pages/_document' { 130 | declare module.exports: any; 131 | } 132 | 133 | declare module 'next/dist/pages/_error' { 134 | declare module.exports: any; 135 | } 136 | 137 | declare module 'next/dist/server/build/babel/find-config' { 138 | declare module.exports: any; 139 | } 140 | 141 | declare module 'next/dist/server/build/babel/plugins/handle-import' { 142 | declare module.exports: any; 143 | } 144 | 145 | declare module 'next/dist/server/build/babel/preset' { 146 | declare module.exports: any; 147 | } 148 | 149 | declare module 'next/dist/server/build/clean' { 150 | declare module.exports: any; 151 | } 152 | 153 | declare module 'next/dist/server/build/index' { 154 | declare module.exports: any; 155 | } 156 | 157 | declare module 'next/dist/server/build/loaders/emit-file-loader' { 158 | declare module.exports: any; 159 | } 160 | 161 | declare module 'next/dist/server/build/loaders/hot-self-accept-loader' { 162 | declare module.exports: any; 163 | } 164 | 165 | declare module 'next/dist/server/build/plugins/combine-assets-plugin' { 166 | declare module.exports: any; 167 | } 168 | 169 | declare module 'next/dist/server/build/plugins/dynamic-chunks-plugin' { 170 | declare module.exports: any; 171 | } 172 | 173 | declare module 'next/dist/server/build/plugins/pages-plugin' { 174 | declare module.exports: any; 175 | } 176 | 177 | declare module 'next/dist/server/build/plugins/unlink-file-plugin' { 178 | declare module.exports: any; 179 | } 180 | 181 | declare module 'next/dist/server/build/plugins/watch-pages-plugin' { 182 | declare module.exports: any; 183 | } 184 | 185 | declare module 'next/dist/server/build/replace' { 186 | declare module.exports: any; 187 | } 188 | 189 | declare module 'next/dist/server/build/root-module-relative-path' { 190 | declare module.exports: any; 191 | } 192 | 193 | declare module 'next/dist/server/build/webpack' { 194 | declare module.exports: any; 195 | } 196 | 197 | declare module 'next/dist/server/config' { 198 | declare module.exports: any; 199 | } 200 | 201 | declare module 'next/dist/server/document' { 202 | declare module.exports: any; 203 | } 204 | 205 | declare module 'next/dist/server/export' { 206 | declare module.exports: any; 207 | } 208 | 209 | declare module 'next/dist/server/hot-reloader' { 210 | declare module.exports: any; 211 | } 212 | 213 | declare module 'next/dist/server/index' { 214 | declare module.exports: any; 215 | } 216 | 217 | declare module 'next/dist/server/next' { 218 | declare module.exports: any; 219 | } 220 | 221 | declare module 'next/dist/server/on-demand-entry-handler' { 222 | declare module.exports: any; 223 | } 224 | 225 | declare module 'next/dist/server/render' { 226 | declare module.exports: any; 227 | } 228 | 229 | declare module 'next/dist/server/require' { 230 | declare module.exports: any; 231 | } 232 | 233 | declare module 'next/dist/server/resolve' { 234 | declare module.exports: any; 235 | } 236 | 237 | declare module 'next/dist/server/router' { 238 | declare module.exports: any; 239 | } 240 | 241 | declare module 'next/dist/server/utils' { 242 | declare module.exports: any; 243 | } 244 | 245 | declare module 'next/document' { 246 | declare module.exports: any; 247 | } 248 | 249 | declare module 'next/dynamic' { 250 | declare module.exports: any; 251 | } 252 | 253 | declare module 'next/error' { 254 | declare module.exports: any; 255 | } 256 | 257 | declare module 'next/head' { 258 | declare module.exports: any; 259 | } 260 | 261 | declare module 'next/link' { 262 | declare module.exports: any; 263 | } 264 | 265 | declare module 'next/prefetch' { 266 | declare module.exports: any; 267 | } 268 | 269 | declare module 'next/router' { 270 | declare module.exports: any; 271 | } 272 | 273 | // Filename aliases 274 | declare module 'next/babel.js' { 275 | declare module.exports: $Exports<'next/babel'>; 276 | } 277 | declare module 'next/client.js' { 278 | declare module.exports: $Exports<'next/client'>; 279 | } 280 | declare module 'next/css.js' { 281 | declare module.exports: $Exports<'next/css'>; 282 | } 283 | declare module 'next/dist/client/head-manager.js' { 284 | declare module.exports: $Exports<'next/dist/client/head-manager'>; 285 | } 286 | declare module 'next/dist/client/index.js' { 287 | declare module.exports: $Exports<'next/dist/client/index'>; 288 | } 289 | declare module 'next/dist/client/next-dev.js' { 290 | declare module.exports: $Exports<'next/dist/client/next-dev'>; 291 | } 292 | declare module 'next/dist/client/next.js' { 293 | declare module.exports: $Exports<'next/dist/client/next'>; 294 | } 295 | declare module 'next/dist/client/on-demand-entries-client.js' { 296 | declare module.exports: $Exports<'next/dist/client/on-demand-entries-client'>; 297 | } 298 | declare module 'next/dist/client/webpack-hot-middleware-client.js' { 299 | declare module.exports: $Exports<'next/dist/client/webpack-hot-middleware-client'>; 300 | } 301 | declare module 'next/dist/lib/app.js' { 302 | declare module.exports: $Exports<'next/dist/lib/app'>; 303 | } 304 | declare module 'next/dist/lib/css.js' { 305 | declare module.exports: $Exports<'next/dist/lib/css'>; 306 | } 307 | declare module 'next/dist/lib/dynamic.js' { 308 | declare module.exports: $Exports<'next/dist/lib/dynamic'>; 309 | } 310 | declare module 'next/dist/lib/error-debug.js' { 311 | declare module.exports: $Exports<'next/dist/lib/error-debug'>; 312 | } 313 | declare module 'next/dist/lib/error.js' { 314 | declare module.exports: $Exports<'next/dist/lib/error'>; 315 | } 316 | declare module 'next/dist/lib/EventEmitter.js' { 317 | declare module.exports: $Exports<'next/dist/lib/EventEmitter'>; 318 | } 319 | declare module 'next/dist/lib/head.js' { 320 | declare module.exports: $Exports<'next/dist/lib/head'>; 321 | } 322 | declare module 'next/dist/lib/link.js' { 323 | declare module.exports: $Exports<'next/dist/lib/link'>; 324 | } 325 | declare module 'next/dist/lib/p-queue.js' { 326 | declare module.exports: $Exports<'next/dist/lib/p-queue'>; 327 | } 328 | declare module 'next/dist/lib/page-loader.js' { 329 | declare module.exports: $Exports<'next/dist/lib/page-loader'>; 330 | } 331 | declare module 'next/dist/lib/prefetch.js' { 332 | declare module.exports: $Exports<'next/dist/lib/prefetch'>; 333 | } 334 | declare module 'next/dist/lib/router/index.js' { 335 | declare module.exports: $Exports<'next/dist/lib/router/index'>; 336 | } 337 | declare module 'next/dist/lib/router/router.js' { 338 | declare module.exports: $Exports<'next/dist/lib/router/router'>; 339 | } 340 | declare module 'next/dist/lib/router/with-router.js' { 341 | declare module.exports: $Exports<'next/dist/lib/router/with-router'>; 342 | } 343 | declare module 'next/dist/lib/shallow-equals.js' { 344 | declare module.exports: $Exports<'next/dist/lib/shallow-equals'>; 345 | } 346 | declare module 'next/dist/lib/side-effect.js' { 347 | declare module.exports: $Exports<'next/dist/lib/side-effect'>; 348 | } 349 | declare module 'next/dist/lib/utils.js' { 350 | declare module.exports: $Exports<'next/dist/lib/utils'>; 351 | } 352 | declare module 'next/dist/pages/_document.js' { 353 | declare module.exports: $Exports<'next/dist/pages/_document'>; 354 | } 355 | declare module 'next/dist/pages/_error.js' { 356 | declare module.exports: $Exports<'next/dist/pages/_error'>; 357 | } 358 | declare module 'next/dist/server/build/babel/find-config.js' { 359 | declare module.exports: $Exports<'next/dist/server/build/babel/find-config'>; 360 | } 361 | declare module 'next/dist/server/build/babel/plugins/handle-import.js' { 362 | declare module.exports: $Exports<'next/dist/server/build/babel/plugins/handle-import'>; 363 | } 364 | declare module 'next/dist/server/build/babel/preset.js' { 365 | declare module.exports: $Exports<'next/dist/server/build/babel/preset'>; 366 | } 367 | declare module 'next/dist/server/build/clean.js' { 368 | declare module.exports: $Exports<'next/dist/server/build/clean'>; 369 | } 370 | declare module 'next/dist/server/build/index.js' { 371 | declare module.exports: $Exports<'next/dist/server/build/index'>; 372 | } 373 | declare module 'next/dist/server/build/loaders/emit-file-loader.js' { 374 | declare module.exports: $Exports<'next/dist/server/build/loaders/emit-file-loader'>; 375 | } 376 | declare module 'next/dist/server/build/loaders/hot-self-accept-loader.js' { 377 | declare module.exports: $Exports<'next/dist/server/build/loaders/hot-self-accept-loader'>; 378 | } 379 | declare module 'next/dist/server/build/plugins/combine-assets-plugin.js' { 380 | declare module.exports: $Exports<'next/dist/server/build/plugins/combine-assets-plugin'>; 381 | } 382 | declare module 'next/dist/server/build/plugins/dynamic-chunks-plugin.js' { 383 | declare module.exports: $Exports<'next/dist/server/build/plugins/dynamic-chunks-plugin'>; 384 | } 385 | declare module 'next/dist/server/build/plugins/pages-plugin.js' { 386 | declare module.exports: $Exports<'next/dist/server/build/plugins/pages-plugin'>; 387 | } 388 | declare module 'next/dist/server/build/plugins/unlink-file-plugin.js' { 389 | declare module.exports: $Exports<'next/dist/server/build/plugins/unlink-file-plugin'>; 390 | } 391 | declare module 'next/dist/server/build/plugins/watch-pages-plugin.js' { 392 | declare module.exports: $Exports<'next/dist/server/build/plugins/watch-pages-plugin'>; 393 | } 394 | declare module 'next/dist/server/build/replace.js' { 395 | declare module.exports: $Exports<'next/dist/server/build/replace'>; 396 | } 397 | declare module 'next/dist/server/build/root-module-relative-path.js' { 398 | declare module.exports: $Exports<'next/dist/server/build/root-module-relative-path'>; 399 | } 400 | declare module 'next/dist/server/build/webpack.js' { 401 | declare module.exports: $Exports<'next/dist/server/build/webpack'>; 402 | } 403 | declare module 'next/dist/server/config.js' { 404 | declare module.exports: $Exports<'next/dist/server/config'>; 405 | } 406 | declare module 'next/dist/server/document.js' { 407 | declare module.exports: $Exports<'next/dist/server/document'>; 408 | } 409 | declare module 'next/dist/server/export.js' { 410 | declare module.exports: $Exports<'next/dist/server/export'>; 411 | } 412 | declare module 'next/dist/server/hot-reloader.js' { 413 | declare module.exports: $Exports<'next/dist/server/hot-reloader'>; 414 | } 415 | declare module 'next/dist/server/index.js' { 416 | declare module.exports: $Exports<'next/dist/server/index'>; 417 | } 418 | declare module 'next/dist/server/next.js' { 419 | declare module.exports: $Exports<'next/dist/server/next'>; 420 | } 421 | declare module 'next/dist/server/on-demand-entry-handler.js' { 422 | declare module.exports: $Exports<'next/dist/server/on-demand-entry-handler'>; 423 | } 424 | declare module 'next/dist/server/render.js' { 425 | declare module.exports: $Exports<'next/dist/server/render'>; 426 | } 427 | declare module 'next/dist/server/require.js' { 428 | declare module.exports: $Exports<'next/dist/server/require'>; 429 | } 430 | declare module 'next/dist/server/resolve.js' { 431 | declare module.exports: $Exports<'next/dist/server/resolve'>; 432 | } 433 | declare module 'next/dist/server/router.js' { 434 | declare module.exports: $Exports<'next/dist/server/router'>; 435 | } 436 | declare module 'next/dist/server/utils.js' { 437 | declare module.exports: $Exports<'next/dist/server/utils'>; 438 | } 439 | declare module 'next/document.js' { 440 | declare module.exports: $Exports<'next/document'>; 441 | } 442 | declare module 'next/dynamic.js' { 443 | declare module.exports: $Exports<'next/dynamic'>; 444 | } 445 | declare module 'next/error.js' { 446 | declare module.exports: $Exports<'next/error'>; 447 | } 448 | declare module 'next/head.js' { 449 | declare module.exports: $Exports<'next/head'>; 450 | } 451 | declare module 'next/link.js' { 452 | declare module.exports: $Exports<'next/link'>; 453 | } 454 | declare module 'next/prefetch.js' { 455 | declare module.exports: $Exports<'next/prefetch'>; 456 | } 457 | declare module 'next/router.js' { 458 | declare module.exports: $Exports<'next/router'>; 459 | } 460 | -------------------------------------------------------------------------------- /flow-typed/npm/jest_v22.x.x.js: -------------------------------------------------------------------------------- 1 | // flow-typed signature: 6e1fc0a644aa956f79029fec0709e597 2 | // flow-typed version: 07ebad4796/jest_v22.x.x/flow_>=v0.39.x 3 | 4 | type JestMockFn, TReturn> = { 5 | (...args: TArguments): TReturn, 6 | /** 7 | * An object for introspecting mock calls 8 | */ 9 | mock: { 10 | /** 11 | * An array that represents all calls that have been made into this mock 12 | * function. Each call is represented by an array of arguments that were 13 | * passed during the call. 14 | */ 15 | calls: Array, 16 | /** 17 | * An array that contains all the object instances that have been 18 | * instantiated from this mock function. 19 | */ 20 | instances: Array 21 | }, 22 | /** 23 | * Resets all information stored in the mockFn.mock.calls and 24 | * mockFn.mock.instances arrays. Often this is useful when you want to clean 25 | * up a mock's usage data between two assertions. 26 | */ 27 | mockClear(): void, 28 | /** 29 | * Resets all information stored in the mock. This is useful when you want to 30 | * completely restore a mock back to its initial state. 31 | */ 32 | mockReset(): void, 33 | /** 34 | * Removes the mock and restores the initial implementation. This is useful 35 | * when you want to mock functions in certain test cases and restore the 36 | * original implementation in others. Beware that mockFn.mockRestore only 37 | * works when mock was created with jest.spyOn. Thus you have to take care of 38 | * restoration yourself when manually assigning jest.fn(). 39 | */ 40 | mockRestore(): void, 41 | /** 42 | * Accepts a function that should be used as the implementation of the mock. 43 | * The mock itself will still record all calls that go into and instances 44 | * that come from itself -- the only difference is that the implementation 45 | * will also be executed when the mock is called. 46 | */ 47 | mockImplementation( 48 | fn: (...args: TArguments) => TReturn 49 | ): JestMockFn, 50 | /** 51 | * Accepts a function that will be used as an implementation of the mock for 52 | * one call to the mocked function. Can be chained so that multiple function 53 | * calls produce different results. 54 | */ 55 | mockImplementationOnce( 56 | fn: (...args: TArguments) => TReturn 57 | ): JestMockFn, 58 | /** 59 | * Just a simple sugar function for returning `this` 60 | */ 61 | mockReturnThis(): void, 62 | /** 63 | * Deprecated: use jest.fn(() => value) instead 64 | */ 65 | mockReturnValue(value: TReturn): JestMockFn, 66 | /** 67 | * Sugar for only returning a value once inside your mock 68 | */ 69 | mockReturnValueOnce(value: TReturn): JestMockFn 70 | }; 71 | 72 | type JestAsymmetricEqualityType = { 73 | /** 74 | * A custom Jasmine equality tester 75 | */ 76 | asymmetricMatch(value: mixed): boolean 77 | }; 78 | 79 | type JestCallsType = { 80 | allArgs(): mixed, 81 | all(): mixed, 82 | any(): boolean, 83 | count(): number, 84 | first(): mixed, 85 | mostRecent(): mixed, 86 | reset(): void 87 | }; 88 | 89 | type JestClockType = { 90 | install(): void, 91 | mockDate(date: Date): void, 92 | tick(milliseconds?: number): void, 93 | uninstall(): void 94 | }; 95 | 96 | type JestMatcherResult = { 97 | message?: string | (() => string), 98 | pass: boolean 99 | }; 100 | 101 | type JestMatcher = (actual: any, expected: any) => JestMatcherResult; 102 | 103 | type JestPromiseType = { 104 | /** 105 | * Use rejects to unwrap the reason of a rejected promise so any other 106 | * matcher can be chained. If the promise is fulfilled the assertion fails. 107 | */ 108 | rejects: JestExpectType, 109 | /** 110 | * Use resolves to unwrap the value of a fulfilled promise so any other 111 | * matcher can be chained. If the promise is rejected the assertion fails. 112 | */ 113 | resolves: JestExpectType 114 | }; 115 | 116 | /** 117 | * Plugin: jest-enzyme 118 | */ 119 | type EnzymeMatchersType = { 120 | toBeChecked(): void, 121 | toBeDisabled(): void, 122 | toBeEmpty(): void, 123 | toBePresent(): void, 124 | toContainReact(element: React$Element): void, 125 | toHaveClassName(className: string): void, 126 | toHaveHTML(html: string): void, 127 | toHaveProp(propKey: string, propValue?: any): void, 128 | toHaveRef(refName: string): void, 129 | toHaveState(stateKey: string, stateValue?: any): void, 130 | toHaveStyle(styleKey: string, styleValue?: any): void, 131 | toHaveTagName(tagName: string): void, 132 | toHaveText(text: string): void, 133 | toIncludeText(text: string): void, 134 | toHaveValue(value: any): void, 135 | toMatchElement(element: React$Element): void, 136 | toMatchSelector(selector: string): void 137 | }; 138 | 139 | type JestExpectType = { 140 | not: JestExpectType & EnzymeMatchersType, 141 | /** 142 | * If you have a mock function, you can use .lastCalledWith to test what 143 | * arguments it was last called with. 144 | */ 145 | lastCalledWith(...args: Array): void, 146 | /** 147 | * toBe just checks that a value is what you expect. It uses === to check 148 | * strict equality. 149 | */ 150 | toBe(value: any): void, 151 | /** 152 | * Use .toHaveBeenCalled to ensure that a mock function got called. 153 | */ 154 | toBeCalled(): void, 155 | /** 156 | * Use .toBeCalledWith to ensure that a mock function was called with 157 | * specific arguments. 158 | */ 159 | toBeCalledWith(...args: Array): void, 160 | /** 161 | * Using exact equality with floating point numbers is a bad idea. Rounding 162 | * means that intuitive things fail. 163 | */ 164 | toBeCloseTo(num: number, delta: any): void, 165 | /** 166 | * Use .toBeDefined to check that a variable is not undefined. 167 | */ 168 | toBeDefined(): void, 169 | /** 170 | * Use .toBeFalsy when you don't care what a value is, you just want to 171 | * ensure a value is false in a boolean context. 172 | */ 173 | toBeFalsy(): void, 174 | /** 175 | * To compare floating point numbers, you can use toBeGreaterThan. 176 | */ 177 | toBeGreaterThan(number: number): void, 178 | /** 179 | * To compare floating point numbers, you can use toBeGreaterThanOrEqual. 180 | */ 181 | toBeGreaterThanOrEqual(number: number): void, 182 | /** 183 | * To compare floating point numbers, you can use toBeLessThan. 184 | */ 185 | toBeLessThan(number: number): void, 186 | /** 187 | * To compare floating point numbers, you can use toBeLessThanOrEqual. 188 | */ 189 | toBeLessThanOrEqual(number: number): void, 190 | /** 191 | * Use .toBeInstanceOf(Class) to check that an object is an instance of a 192 | * class. 193 | */ 194 | toBeInstanceOf(cls: Class<*>): void, 195 | /** 196 | * .toBeNull() is the same as .toBe(null) but the error messages are a bit 197 | * nicer. 198 | */ 199 | toBeNull(): void, 200 | /** 201 | * Use .toBeTruthy when you don't care what a value is, you just want to 202 | * ensure a value is true in a boolean context. 203 | */ 204 | toBeTruthy(): void, 205 | /** 206 | * Use .toBeUndefined to check that a variable is undefined. 207 | */ 208 | toBeUndefined(): void, 209 | /** 210 | * Use .toContain when you want to check that an item is in a list. For 211 | * testing the items in the list, this uses ===, a strict equality check. 212 | */ 213 | toContain(item: any): void, 214 | /** 215 | * Use .toContainEqual when you want to check that an item is in a list. For 216 | * testing the items in the list, this matcher recursively checks the 217 | * equality of all fields, rather than checking for object identity. 218 | */ 219 | toContainEqual(item: any): void, 220 | /** 221 | * Use .toEqual when you want to check that two objects have the same value. 222 | * This matcher recursively checks the equality of all fields, rather than 223 | * checking for object identity. 224 | */ 225 | toEqual(value: any): void, 226 | /** 227 | * Use .toHaveBeenCalled to ensure that a mock function got called. 228 | */ 229 | toHaveBeenCalled(): void, 230 | /** 231 | * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact 232 | * number of times. 233 | */ 234 | toHaveBeenCalledTimes(number: number): void, 235 | /** 236 | * Use .toHaveBeenCalledWith to ensure that a mock function was called with 237 | * specific arguments. 238 | */ 239 | toHaveBeenCalledWith(...args: Array): void, 240 | /** 241 | * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called 242 | * with specific arguments. 243 | */ 244 | toHaveBeenLastCalledWith(...args: Array): void, 245 | /** 246 | * Check that an object has a .length property and it is set to a certain 247 | * numeric value. 248 | */ 249 | toHaveLength(number: number): void, 250 | /** 251 | * 252 | */ 253 | toHaveProperty(propPath: string, value?: any): void, 254 | /** 255 | * Use .toMatch to check that a string matches a regular expression or string. 256 | */ 257 | toMatch(regexpOrString: RegExp | string): void, 258 | /** 259 | * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object. 260 | */ 261 | toMatchObject(object: Object | Array): void, 262 | /** 263 | * This ensures that a React component matches the most recent snapshot. 264 | */ 265 | toMatchSnapshot(name?: string): void, 266 | /** 267 | * Use .toThrow to test that a function throws when it is called. 268 | * If you want to test that a specific error gets thrown, you can provide an 269 | * argument to toThrow. The argument can be a string for the error message, 270 | * a class for the error, or a regex that should match the error. 271 | * 272 | * Alias: .toThrowError 273 | */ 274 | toThrow(message?: string | Error | Class | RegExp): void, 275 | toThrowError(message?: string | Error | Class | RegExp): void, 276 | /** 277 | * Use .toThrowErrorMatchingSnapshot to test that a function throws a error 278 | * matching the most recent snapshot when it is called. 279 | */ 280 | toThrowErrorMatchingSnapshot(): void 281 | }; 282 | 283 | type JestObjectType = { 284 | /** 285 | * Disables automatic mocking in the module loader. 286 | * 287 | * After this method is called, all `require()`s will return the real 288 | * versions of each module (rather than a mocked version). 289 | */ 290 | disableAutomock(): JestObjectType, 291 | /** 292 | * An un-hoisted version of disableAutomock 293 | */ 294 | autoMockOff(): JestObjectType, 295 | /** 296 | * Enables automatic mocking in the module loader. 297 | */ 298 | enableAutomock(): JestObjectType, 299 | /** 300 | * An un-hoisted version of enableAutomock 301 | */ 302 | autoMockOn(): JestObjectType, 303 | /** 304 | * Clears the mock.calls and mock.instances properties of all mocks. 305 | * Equivalent to calling .mockClear() on every mocked function. 306 | */ 307 | clearAllMocks(): JestObjectType, 308 | /** 309 | * Resets the state of all mocks. Equivalent to calling .mockReset() on every 310 | * mocked function. 311 | */ 312 | resetAllMocks(): JestObjectType, 313 | /** 314 | * Restores all mocks back to their original value. 315 | */ 316 | restoreAllMocks(): JestObjectType, 317 | /** 318 | * Removes any pending timers from the timer system. 319 | */ 320 | clearAllTimers(): void, 321 | /** 322 | * The same as `mock` but not moved to the top of the expectation by 323 | * babel-jest. 324 | */ 325 | doMock(moduleName: string, moduleFactory?: any): JestObjectType, 326 | /** 327 | * The same as `unmock` but not moved to the top of the expectation by 328 | * babel-jest. 329 | */ 330 | dontMock(moduleName: string): JestObjectType, 331 | /** 332 | * Returns a new, unused mock function. Optionally takes a mock 333 | * implementation. 334 | */ 335 | fn, TReturn>( 336 | implementation?: (...args: TArguments) => TReturn 337 | ): JestMockFn, 338 | /** 339 | * Determines if the given function is a mocked function. 340 | */ 341 | isMockFunction(fn: Function): boolean, 342 | /** 343 | * Given the name of a module, use the automatic mocking system to generate a 344 | * mocked version of the module for you. 345 | */ 346 | genMockFromModule(moduleName: string): any, 347 | /** 348 | * Mocks a module with an auto-mocked version when it is being required. 349 | * 350 | * The second argument can be used to specify an explicit module factory that 351 | * is being run instead of using Jest's automocking feature. 352 | * 353 | * The third argument can be used to create virtual mocks -- mocks of modules 354 | * that don't exist anywhere in the system. 355 | */ 356 | mock( 357 | moduleName: string, 358 | moduleFactory?: any, 359 | options?: Object 360 | ): JestObjectType, 361 | /** 362 | * Returns the actual module instead of a mock, bypassing all checks on 363 | * whether the module should receive a mock implementation or not. 364 | */ 365 | requireActual(moduleName: string): any, 366 | /** 367 | * Returns a mock module instead of the actual module, bypassing all checks 368 | * on whether the module should be required normally or not. 369 | */ 370 | requireMock(moduleName: string): any, 371 | /** 372 | * Resets the module registry - the cache of all required modules. This is 373 | * useful to isolate modules where local state might conflict between tests. 374 | */ 375 | resetModules(): JestObjectType, 376 | /** 377 | * Exhausts the micro-task queue (usually interfaced in node via 378 | * process.nextTick). 379 | */ 380 | runAllTicks(): void, 381 | /** 382 | * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(), 383 | * setInterval(), and setImmediate()). 384 | */ 385 | runAllTimers(): void, 386 | /** 387 | * Exhausts all tasks queued by setImmediate(). 388 | */ 389 | runAllImmediates(): void, 390 | /** 391 | * Executes only the macro task queue (i.e. all tasks queued by setTimeout() 392 | * or setInterval() and setImmediate()). 393 | */ 394 | runTimersToTime(msToRun: number): void, 395 | /** 396 | * Executes only the macro-tasks that are currently pending (i.e., only the 397 | * tasks that have been queued by setTimeout() or setInterval() up to this 398 | * point) 399 | */ 400 | runOnlyPendingTimers(): void, 401 | /** 402 | * Explicitly supplies the mock object that the module system should return 403 | * for the specified module. Note: It is recommended to use jest.mock() 404 | * instead. 405 | */ 406 | setMock(moduleName: string, moduleExports: any): JestObjectType, 407 | /** 408 | * Indicates that the module system should never return a mocked version of 409 | * the specified module from require() (e.g. that it should always return the 410 | * real module). 411 | */ 412 | unmock(moduleName: string): JestObjectType, 413 | /** 414 | * Instructs Jest to use fake versions of the standard timer functions 415 | * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick, 416 | * setImmediate and clearImmediate). 417 | */ 418 | useFakeTimers(): JestObjectType, 419 | /** 420 | * Instructs Jest to use the real versions of the standard timer functions. 421 | */ 422 | useRealTimers(): JestObjectType, 423 | /** 424 | * Creates a mock function similar to jest.fn but also tracks calls to 425 | * object[methodName]. 426 | */ 427 | spyOn(object: Object, methodName: string): JestMockFn, 428 | /** 429 | * Set the default timeout interval for tests and before/after hooks in milliseconds. 430 | * Note: The default timeout interval is 5 seconds if this method is not called. 431 | */ 432 | setTimeout(timeout: number): JestObjectType 433 | }; 434 | 435 | type JestSpyType = { 436 | calls: JestCallsType 437 | }; 438 | 439 | /** Runs this function after every test inside this context */ 440 | declare function afterEach( 441 | fn: (done: () => void) => ?Promise, 442 | timeout?: number 443 | ): void; 444 | /** Runs this function before every test inside this context */ 445 | declare function beforeEach( 446 | fn: (done: () => void) => ?Promise, 447 | timeout?: number 448 | ): void; 449 | /** Runs this function after all tests have finished inside this context */ 450 | declare function afterAll( 451 | fn: (done: () => void) => ?Promise, 452 | timeout?: number 453 | ): void; 454 | /** Runs this function before any tests have started inside this context */ 455 | declare function beforeAll( 456 | fn: (done: () => void) => ?Promise, 457 | timeout?: number 458 | ): void; 459 | 460 | /** A context for grouping tests together */ 461 | declare var describe: { 462 | /** 463 | * Creates a block that groups together several related tests in one "test suite" 464 | */ 465 | (name: string, fn: () => void): void, 466 | 467 | /** 468 | * Only run this describe block 469 | */ 470 | only(name: string, fn: () => void): void, 471 | 472 | /** 473 | * Skip running this describe block 474 | */ 475 | skip(name: string, fn: () => void): void 476 | }; 477 | 478 | /** An individual test unit */ 479 | declare var it: { 480 | /** 481 | * An individual test unit 482 | * 483 | * @param {string} Name of Test 484 | * @param {Function} Test 485 | * @param {number} Timeout for the test, in milliseconds. 486 | */ 487 | ( 488 | name: string, 489 | fn?: (done: () => void) => ?Promise, 490 | timeout?: number 491 | ): void, 492 | /** 493 | * Only run this test 494 | * 495 | * @param {string} Name of Test 496 | * @param {Function} Test 497 | * @param {number} Timeout for the test, in milliseconds. 498 | */ 499 | only( 500 | name: string, 501 | fn?: (done: () => void) => ?Promise, 502 | timeout?: number 503 | ): void, 504 | /** 505 | * Skip running this test 506 | * 507 | * @param {string} Name of Test 508 | * @param {Function} Test 509 | * @param {number} Timeout for the test, in milliseconds. 510 | */ 511 | skip( 512 | name: string, 513 | fn?: (done: () => void) => ?Promise, 514 | timeout?: number 515 | ): void, 516 | /** 517 | * Run the test concurrently 518 | * 519 | * @param {string} Name of Test 520 | * @param {Function} Test 521 | * @param {number} Timeout for the test, in milliseconds. 522 | */ 523 | concurrent( 524 | name: string, 525 | fn?: (done: () => void) => ?Promise, 526 | timeout?: number 527 | ): void 528 | }; 529 | declare function fit( 530 | name: string, 531 | fn: (done: () => void) => ?Promise, 532 | timeout?: number 533 | ): void; 534 | /** An individual test unit */ 535 | declare var test: typeof it; 536 | /** A disabled group of tests */ 537 | declare var xdescribe: typeof describe; 538 | /** A focused group of tests */ 539 | declare var fdescribe: typeof describe; 540 | /** A disabled individual test */ 541 | declare var xit: typeof it; 542 | /** A disabled individual test */ 543 | declare var xtest: typeof it; 544 | 545 | /** The expect function is used every time you want to test a value */ 546 | declare var expect: { 547 | /** The object that you want to make assertions against */ 548 | (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType, 549 | /** Add additional Jasmine matchers to Jest's roster */ 550 | extend(matchers: { [name: string]: JestMatcher }): void, 551 | /** Add a module that formats application-specific data structures. */ 552 | addSnapshotSerializer(serializer: (input: Object) => string): void, 553 | assertions(expectedAssertions: number): void, 554 | hasAssertions(): void, 555 | any(value: mixed): JestAsymmetricEqualityType, 556 | anything(): void, 557 | arrayContaining(value: Array): void, 558 | objectContaining(value: Object): void, 559 | /** Matches any received string that contains the exact expected string. */ 560 | stringContaining(value: string): void, 561 | stringMatching(value: string | RegExp): void 562 | }; 563 | 564 | // TODO handle return type 565 | // http://jasmine.github.io/2.4/introduction.html#section-Spies 566 | declare function spyOn(value: mixed, method: string): Object; 567 | 568 | /** Holds all functions related to manipulating test runner */ 569 | declare var jest: JestObjectType; 570 | 571 | /** 572 | * The global Jasmine object, this is generally not exposed as the public API, 573 | * using features inside here could break in later versions of Jest. 574 | */ 575 | declare var jasmine: { 576 | DEFAULT_TIMEOUT_INTERVAL: number, 577 | any(value: mixed): JestAsymmetricEqualityType, 578 | anything(): void, 579 | arrayContaining(value: Array): void, 580 | clock(): JestClockType, 581 | createSpy(name: string): JestSpyType, 582 | createSpyObj( 583 | baseName: string, 584 | methodNames: Array 585 | ): { [methodName: string]: JestSpyType }, 586 | objectContaining(value: Object): void, 587 | stringMatching(value: string): void 588 | }; 589 | --------------------------------------------------------------------------------