Skip to content

Commit

Permalink
init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pshrmn committed Mar 14, 2017
0 parents commit 12a4118
Show file tree
Hide file tree
Showing 8 changed files with 400 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .babelrc
@@ -0,0 +1,6 @@
{
"presets": ["es2015"],
"plugins": [
"transform-object-rest-spread"
]
}
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
node_modules
*.log
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Paul Sherman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
18 changes: 18 additions & 0 deletions README.md
@@ -0,0 +1,18 @@
# react-router-test-context

Create a pseudo `context` object that duplicates React Router's `context.router` structure. This is useful for shallow unit testing with Enzyme.

### Usage

```js
import createRouterContext from 'react-router-test-context'
import { shallow } from 'enzyme'

describe('my test', () => {
it('renders', () => {
const context = createRouterContext()
const wrapper = shallow(<MyComponent />, { context })
// ...
})
})
```
83 changes: 83 additions & 0 deletions index.js
@@ -0,0 +1,83 @@
'use strict';

Object.defineProperty(exports, "__esModule", {
value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var randomKey = function randomKey(keyLength) {
return Math.random().toString(36).substr(2, keyLength);
};

var createDefaultMatch = function createDefaultMatch() {
return { path: '/', url: '/', isExact: true, params: {} };
};

var createDefaultLocation = function createDefaultLocation() {
return { pathname: '/', search: '', hash: '', key: randomKey(6) };
};

var createDefaultHistory = function createDefaultHistory(location) {
return {
action: 'POP',
location: location || createDefaultLocation(),
_listeners: [],
listen: function listen(fn) {
var _this = this;

this._listeners.push(fn);
return function () {
_this._listeners = _this._listeners.filter(function (func) {
return func !== fn;
});
};
},
push: function push(location) {
this._notifyListeners(location);
},
replace: function replace(location) {
this._notifyListeners(location);
},
_notifyListeners: function _notifyListeners(loc) {
this._listeners.forEach(function (fn) {
fn(loc);
});
},
createHref: function createHref(loc) {
if (typeof loc === 'string') {
return loc;
} else {
return loc.pathname + (loc.search || '') + (loc.hash || '');
}
}
};
};

var createRouterContext = function createRouterContext() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var userHistory = options.history,
userLocation = options.location,
userMatch = options.match,
staticContext = options.staticContext;


var match = _extends({}, createDefaultMatch(), userMatch);

var location = _extends({}, createDefaultLocation(), userLocation);

var history = _extends({}, createDefaultHistory(location), userHistory);

return {
router: {
history: history,
route: {
match: match,
location: location
},
staticContext: staticContext
}
};
};

exports.default = createRouterContext;
39 changes: 39 additions & 0 deletions package.json
@@ -0,0 +1,39 @@
{
"name": "react-router-test-context",
"version": "0.1.0",
"description": "Create a pseudo context to assist in testing components that render React Router's location-aware components.",
"main": "index.js",
"files": [
"index.js",
"LICENSE",
"*.md"
],
"scripts": {
"build": "babel ./src -o index.js --ignore __tests__",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git://github.com/pshrmn/react-router-test-context.git"
},
"keywords": [
"React",
"React",
"Router",
"unit",
"test"
],
"author": "Paul Sherman",
"license": "MIT",
"bugs": {
"url": "https://github.com/pshrmn/react-router-test-context/issues"
},
"homepage": "https://github.com/pshrmn/react-router-test-context#readme",
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-core": "^6.24.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-preset-es2015": "^6.24.0",
"jest": "^19.0.2"
}
}
162 changes: 162 additions & 0 deletions src/__tests__/index.spec.js
@@ -0,0 +1,162 @@
import createContext from '../index'

describe('createContext', () => {
it('returns an object with a "router" property', () => {
const ctx = createContext()
expect(ctx).toHaveProperty('router')
})

describe('context.router', () => {
it('has expected properties', () => {
const ctx = createContext()
expect(ctx.router).toHaveProperty('history')
expect(ctx.router).toHaveProperty('route')
expect(ctx.router).toHaveProperty('staticContext')
// context.router.route
expect(ctx.router.route).toHaveProperty('match')
expect(ctx.router.route).toHaveProperty('location')
})

describe('match', () => {
it('is default object if not provided', () => {
const ctx = createContext()
const { match } = ctx.router.route
expect(match).toEqual({
path: '/',
url: '/',
isExact: true,
params: {}
})
})

it('is provided object', () => {
const match = {
path: '/:number',
url: '/8',
isExact: true,
params: { number: '8' }
}
const ctx = createContext({ match })
expect(ctx.router.route.match).toEqual(match)
})

it('merges partially provided match object', () => {
const partialMatch = { isExact: false }
const ctx = createContext({ match: partialMatch })
const { match } = ctx.router.route
expect(match).toEqual({
path: '/',
url: '/',
isExact: false,
params: {}
})
})
})

describe('location', () => {
it('is default object if not provided', () => {
const ctx = createContext()
const { location } = ctx.router.route
expect(location.pathname).toBe('/')
expect(location.search).toBe('')
expect(location.hash).toBe('')
expect(typeof location.key).toBe('string')
expect(location.key.length).toBe(6)
})

it('is provided object', () => {
const location = {
pathname: '/some-place',
search: '?test=value',
hash: '#hash',
key: 'okdoke'
}
const ctx = createContext({ location })
expect(ctx.router.route.location).toEqual(location)
})

it('merges partially provided location object', () => {
const partialLocation = { pathname: '/somewhere' }
const ctx = createContext({ location: partialLocation })
const { location } = ctx.router.route
expect(location.pathname).toBe('/somewhere')
expect(location.search).toBe('')
expect(location.hash).toBe('')
})
})

describe('history', () => {
it('is default object if not provided', () => {
const properties = {
action: 'string',
location: 'object',
listen: 'function',
push: 'function',
replace: 'function',
createHref: 'function'
}
const ctx = createContext()
const { history } = ctx.router
Object.keys(properties).forEach(key => {
expect(history).toHaveProperty(key)
expect(typeof history[key]).toBe(properties[key])
})
})

it('uses location option if provided', () => {
const location = { pathname: '/in-history' }
const ctx = createContext({ location })
const { history } = ctx.router
expect(history.location.pathname).toBe(location.pathname)
})

it('is provided object', () => {
const fakeHistory = {
action: 'FAKE_ACTION',
location: {},
listen: () => {},
push: () => {},
replace: () => {},
createHref: () => {}
}
const ctx = createContext({ history: fakeHistory })
const { history } = ctx.router
Object.keys(fakeHistory).forEach(key => {
expect(history[key]).toEqual(fakeHistory[key])
})
})

it('merges partially provided history object', () => {
const partialHistory = {
action: 'FAKE_ACTION'
}
const ctx = createContext({ history: partialHistory })
const { history } = ctx.router

// verify that the partial property is present
expect(history.action).toEqual(partialHistory.action)
// and that the default properties exist
const properties = [ 'action', 'location', 'listen', 'push', 'replace', 'createHref' ]
properties.forEach(p => {
expect(history).toHaveProperty(p)
})
})

})

describe('staticContext', () => {
it('is undefined if not provided as an option', () => {
const ctx = createContext()
expect(ctx.router.staticContext).toBe(undefined)
})

it('is the provided value', () => {
const staticContext = {}
const ctx = createContext({ staticContext })
expect(ctx.router.staticContext).toBe(staticContext)
})
})


})
})

0 comments on commit 12a4118

Please sign in to comment.