Pristine, mapping and tests
This commit is contained in:
parent
a008b1ce8d
commit
15b6df9526
|
|
@ -1,30 +1,4 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
# Commenting this out is preferred by some people, see
|
||||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git-
|
||||
node_modules
|
||||
|
||||
# Users Environment Variables
|
||||
.lock-wscript
|
||||
.DS_Store
|
||||
build/
|
||||
build/index.html
|
||||
build/test.js
|
||||
node_modules
|
||||
|
|
|
|||
138
Gulpfile.js
138
Gulpfile.js
|
|
@ -1,94 +1,130 @@
|
|||
var gulp = require('gulp');
|
||||
var source = require('vinyl-source-stream'); // Used to stream bundle for further handling
|
||||
var browserify = require('browserify');
|
||||
var watchify = require('watchify');
|
||||
var source = require('vinyl-source-stream');
|
||||
var reactify = require('reactify');
|
||||
var gulpif = require('gulp-if');
|
||||
var uglify = require('gulp-uglify');
|
||||
var streamify = require('gulp-streamify');
|
||||
var notify = require('gulp-notify');
|
||||
var gutil = require('gulp-util');
|
||||
var package = require('./package.json');
|
||||
var shell = require('gulp-shell');
|
||||
var reactify = require('reactify');
|
||||
var livereload = require('gulp-livereload');
|
||||
var glob = require('glob');
|
||||
var jasminePhantomJs = require('gulp-jasmine2-phantomjs');
|
||||
var fs = require('fs');
|
||||
|
||||
// The task that handles both development and deployment
|
||||
var runBrowserifyTask = function (options) {
|
||||
var dependencies = ['react'];
|
||||
|
||||
// This bundle is for our application
|
||||
var bundler = browserify({
|
||||
debug: options.debug, // Need that sourcemapping
|
||||
standalone: 'Formsy',
|
||||
// These options are just for Watchify
|
||||
cache: {}, packageCache: {}, fullPaths: options.watch
|
||||
})
|
||||
.require(require.resolve('./src/main.js'), { entry: true })
|
||||
.transform(reactify) // Transform JSX
|
||||
.external('react');
|
||||
var browserifyTask = function (options) {
|
||||
|
||||
// The actual rebundle process
|
||||
// Our app bundler
|
||||
var appBundler = browserify({
|
||||
entries: [options.src],
|
||||
transform: [reactify],
|
||||
debug: options.development,
|
||||
cache: {},
|
||||
packageCache: {},
|
||||
fullPaths: options.development
|
||||
});
|
||||
|
||||
appBundler.external(dependencies);
|
||||
|
||||
// The rebundle process
|
||||
var rebundle = function () {
|
||||
var start = Date.now();
|
||||
bundler.bundle()
|
||||
var fileName = options.uglify ? 'formsy-react.min.js' : 'formsy-react.js';
|
||||
console.log('Building APP bundle');
|
||||
appBundler.bundle()
|
||||
.on('error', gutil.log)
|
||||
.pipe(source(options.name))
|
||||
.pipe(source(fileName))
|
||||
.pipe(gulpif(options.uglify, streamify(uglify())))
|
||||
.pipe(gulp.dest(options.dest))
|
||||
.pipe(notify(function () {
|
||||
console.log('APP bundle built in ' + (Date.now() - start) + 'ms');
|
||||
|
||||
/*
|
||||
// Fix for requirejs
|
||||
var fs = require('fs');
|
||||
var file = fs.readFileSync(options.dest + '/' + options.name).toString();
|
||||
var file = fs.readFileSync(options.dest + '/' + fileName).toString();
|
||||
file = file.replace('define([],e)', 'define(["react"],e)');
|
||||
fs.writeFileSync(options.dest + '/' + options.name, file);
|
||||
|
||||
console.log('Built in ' + (Date.now() - start) + 'ms');
|
||||
|
||||
fs.writeFileSync(options.dest + '/' + fileName, file);
|
||||
*/
|
||||
}));
|
||||
|
||||
};
|
||||
|
||||
// Fire up Watchify when developing
|
||||
if (options.watch) {
|
||||
bundler = watchify(bundler);
|
||||
bundler.on('update', rebundle);
|
||||
if (options.development) {
|
||||
appBundler = watchify(appBundler);
|
||||
appBundler.on('update', rebundle);
|
||||
}
|
||||
|
||||
return rebundle();
|
||||
rebundle();
|
||||
|
||||
};
|
||||
// We create a separate bundle for our dependencies as they
|
||||
// should not rebundle on file changes. This only happens when
|
||||
// we develop. When deploying the dependencies will be included
|
||||
// in the application bundle
|
||||
if (options.development) {
|
||||
|
||||
var testFiles = glob.sync('./specs/**/*-spec.js');
|
||||
var testBundler = browserify({
|
||||
entries: testFiles,
|
||||
debug: true,
|
||||
transform: [reactify],
|
||||
cache: {},
|
||||
packageCache: {},
|
||||
fullPaths: true
|
||||
});
|
||||
|
||||
testBundler.external(dependencies);
|
||||
|
||||
var rebundleTests = function () {
|
||||
var start = Date.now();
|
||||
console.log('Building TEST bundle');
|
||||
testBundler.bundle()
|
||||
.on('error', gutil.log)
|
||||
.pipe(source('specs.js'))
|
||||
.pipe(gulp.dest(options.dest))
|
||||
.pipe(livereload())
|
||||
.pipe(notify(function () {
|
||||
console.log('TEST bundle built in ' + (Date.now() - start) + 'ms');
|
||||
}));
|
||||
};
|
||||
|
||||
testBundler = watchify(testBundler);
|
||||
testBundler.on('update', rebundleTests);
|
||||
rebundleTests();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Starts our development workflow
|
||||
gulp.task('default', function () {
|
||||
|
||||
runBrowserifyTask({
|
||||
watch: true,
|
||||
dest: './build',
|
||||
uglify: false,
|
||||
debug: true,
|
||||
name: 'formsy-react.js'
|
||||
livereload.listen({ basePath: 'specs' });
|
||||
browserifyTask({
|
||||
development: true,
|
||||
src: './src/main.js',
|
||||
dest: './build'
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
gulp.task('deploy', function () {
|
||||
|
||||
runBrowserifyTask({
|
||||
watch: false,
|
||||
dest: './releases',
|
||||
uglify: true,
|
||||
debug: false,
|
||||
name: 'formsy-react.min.js'
|
||||
browserifyTask({
|
||||
development: false,
|
||||
src: './src/main.js',
|
||||
dest: './release'
|
||||
});
|
||||
|
||||
runBrowserifyTask({
|
||||
watch: false,
|
||||
dest: './releases',
|
||||
uglify: false,
|
||||
debug: false,
|
||||
name: 'formsy-react.js'
|
||||
browserifyTask({
|
||||
development: false,
|
||||
src: './src/main.js',
|
||||
dest: './release',
|
||||
uglify: true
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
gulp.task('test', shell.task([
|
||||
'./node_modules/.bin/jasmine-node ./specs --autotest --watch ./src --color'
|
||||
]));
|
||||
|
|
|
|||
57
README.md
57
README.md
|
|
@ -15,6 +15,7 @@ A form input builder and validator for React JS
|
|||
- [url](#url)
|
||||
- [method](#method)
|
||||
- [contentType](#contenttype)
|
||||
- [mapping](#mapping)
|
||||
- [onSuccess()](#onsuccess)
|
||||
- [onSubmit()](#onsubmit)
|
||||
- [onSubmitted()](#onsubmitted)
|
||||
|
|
@ -36,6 +37,7 @@ A form input builder and validator for React JS
|
|||
- [isRequired()](#isrequired)
|
||||
- [showRequired()](#showrequired)
|
||||
- [showError()](#showerror)
|
||||
- [isPristine()](#ispristine)
|
||||
- [Formsy.addValidationRule](#formsyaddvalidationrule)
|
||||
- [Validators](#validators)
|
||||
|
||||
|
|
@ -63,6 +65,13 @@ The main concept is that forms, inputs and validation is done very differently a
|
|||
|
||||
## <a name="changes">Changes</a>
|
||||
|
||||
**0.6.0**
|
||||
- **onSubmit()** now has the same signature regardless of passing url attribute or not
|
||||
- **isPristine()** is a new method to handle "touched" form elements (thanks @FoxxMD)
|
||||
- Mapping attribute to pass a function that maps input values to new structure. The new structure is either passed to *onSubmit* or to the server when using a url attribute (thanks for feedback @MattAitchison)
|
||||
- Added default "equalsField" validation rule
|
||||
- Lots of tests!
|
||||
|
||||
**0.5.2**
|
||||
- Fixed bug with handlers in ajax requests (Thanks @smokku)
|
||||
|
||||
|
|
@ -214,9 +223,11 @@ Takes a function to run when the server has responded with a success http status
|
|||
```html
|
||||
<Formsy.Form url="/users" onSubmit={this.showFormLoader}></Formsy.Form>
|
||||
```
|
||||
Takes a function to run when the submit button has been clicked. The first argument is the data of the form. The second argument will reset the form. The third argument will invalidate the form by taking an object that maps to inputs. E.g. `{email: "This email is taken"}`. Resetting or invalidating the form will cause **setState** to run on the form element component.
|
||||
Takes a function to run when the submit button has been clicked.
|
||||
|
||||
**note!** When resetting the form the form elements needs to bind its current value using the *getValue* method. That will empty for example an input.
|
||||
The first argument is the data of the form. The second argument will reset the form. The third argument will invalidate the form by taking an object that maps to inputs. E.g. `{email: "This email is taken"}`. Resetting or invalidating the form will cause **setState** to run on the form element component.
|
||||
|
||||
**note!** If you do not pass a url attribute this handler is where you would manually do your ajax request.
|
||||
|
||||
#### <a name="onsubmitted">onSubmitted()</a>
|
||||
```html
|
||||
|
|
@ -297,6 +308,7 @@ Gets the current value of the form input component.
|
|||
#### <a name="setvalue">setValue(value)</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -312,6 +324,7 @@ Sets the value of your form input component. Notice that it does not have to be
|
|||
#### <a name="hasvalue">hasValue()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -330,6 +343,7 @@ The hasValue() method helps you identify if there actually is a value or not. Th
|
|||
#### <a name="resetvalue">resetValue()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -348,6 +362,7 @@ Resets to empty value. This will run a **setState()** on the component and do a
|
|||
#### <a name="geterrormessage">getErrorMessage()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -366,6 +381,7 @@ Will return the server error mapped to the form input component or return the va
|
|||
#### <a name="isvalid">isValid()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -386,6 +402,7 @@ Returns the valid state of the form input component.
|
|||
#### <a name="isrequired">isRequired()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -405,6 +422,7 @@ Returns true if the required property has been passed.
|
|||
#### <a name="showrequired">showRequired()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -424,6 +442,7 @@ Lets you check if the form input component should indicate if it is a required f
|
|||
#### <a name="showerror">showError()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
|
|
@ -440,6 +459,28 @@ var MyInput = React.createClass({
|
|||
```
|
||||
Lets you check if the form input component should indicate if there is an error. This happens if there is a form input component value and it is invalid or if a server error is received.
|
||||
|
||||
#### <a name="ispristine">isPristine()</a>
|
||||
```javascript
|
||||
var MyInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
changeValue: function (event) {
|
||||
this.setValue(event.currentTarget.value);
|
||||
},
|
||||
render: function () {
|
||||
return (
|
||||
<div>
|
||||
<input type="text" onChange={this.changeValue} value={this.getValue()}/>
|
||||
<span>{this.isPristine() ? 'You have not touched this yet' : ''}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
```
|
||||
By default all formsy input elements are pristine, which means they are not "touched". As soon as the **setValue** method is run it will no longer be pristine.
|
||||
|
||||
**note!** When the form is reset, using the resetForm callback function on **onSubmit** the inputs are not reset to pristine.
|
||||
|
||||
|
||||
### <a name="formsyaddvalidationrule">Formsy.addValidationRule(name, ruleFunc)</a>
|
||||
An example:
|
||||
```javascript
|
||||
|
|
@ -528,6 +569,18 @@ Returns true if the value length is the equal or more than minimum and equal or
|
|||
```
|
||||
Return true if the value from input component matches value passed (==).
|
||||
|
||||
**equalsField:fieldName**
|
||||
```html
|
||||
<MyInputComponent name="password"/>
|
||||
<MyInputComponent name="repeated_password" validations="equalsField:password"/>
|
||||
```
|
||||
Return true if the value from input component matches value passed (==).
|
||||
|
||||
## Run tests
|
||||
- Run `gulp`
|
||||
- Run a server in `build` folder
|
||||
- Go to `localhost/testrunner.html` (live reload)
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "formsy-react",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"main": "src/main.js",
|
||||
"dependencies": {
|
||||
"react": "^0.11.2"
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,576 @@
|
|||
/*
|
||||
|
||||
Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
|
||||
BDD framework for JavaScript.
|
||||
|
||||
http://github.com/pivotal/jasmine-ajax
|
||||
|
||||
Jasmine Home page: http://pivotal.github.com/jasmine
|
||||
|
||||
Copyright (c) 2008-2013 Pivotal Labs
|
||||
|
||||
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.
|
||||
|
||||
*/
|
||||
|
||||
getJasmineRequireObj().ajax = function(jRequire) {
|
||||
var $ajax = {};
|
||||
|
||||
$ajax.RequestStub = jRequire.AjaxRequestStub();
|
||||
$ajax.RequestTracker = jRequire.AjaxRequestTracker();
|
||||
$ajax.StubTracker = jRequire.AjaxStubTracker();
|
||||
$ajax.ParamParser = jRequire.AjaxParamParser();
|
||||
$ajax.fakeRequest = jRequire.AjaxFakeRequest();
|
||||
$ajax.MockAjax = jRequire.MockAjax($ajax);
|
||||
|
||||
return $ajax.MockAjax;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().AjaxFakeRequest = function() {
|
||||
function extend(destination, source, propertiesToSkip) {
|
||||
propertiesToSkip = propertiesToSkip || [];
|
||||
for (var property in source) {
|
||||
if (!arrayContains(propertiesToSkip, property)) {
|
||||
destination[property] = source[property];
|
||||
}
|
||||
}
|
||||
return destination;
|
||||
}
|
||||
|
||||
function arrayContains(arr, item) {
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
if (arr[i] === item) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function wrapProgressEvent(xhr, eventName) {
|
||||
return function() {
|
||||
if (xhr[eventName]) {
|
||||
xhr[eventName]();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function initializeEvents(xhr) {
|
||||
return {
|
||||
'loadstart': wrapProgressEvent(xhr, 'onloadstart'),
|
||||
'load': wrapProgressEvent(xhr, 'onload'),
|
||||
'loadend': wrapProgressEvent(xhr, 'onloadend'),
|
||||
'progress': wrapProgressEvent(xhr, 'onprogress'),
|
||||
'error': wrapProgressEvent(xhr, 'onerror'),
|
||||
'abort': wrapProgressEvent(xhr, 'onabort'),
|
||||
'timeout': wrapProgressEvent(xhr, 'ontimeout')
|
||||
};
|
||||
}
|
||||
|
||||
function unconvertibleResponseTypeMessage(type) {
|
||||
var msg = [
|
||||
"Can't build XHR.response for XHR.responseType of '",
|
||||
type,
|
||||
"'.",
|
||||
"XHR.response must be explicitly stubbed"
|
||||
];
|
||||
return msg.join(' ');
|
||||
}
|
||||
|
||||
function fakeRequest(global, requestTracker, stubTracker, paramParser) {
|
||||
function FakeXMLHttpRequest() {
|
||||
requestTracker.track(this);
|
||||
this.events = initializeEvents(this);
|
||||
this.requestHeaders = {};
|
||||
this.overriddenMimeType = null;
|
||||
}
|
||||
|
||||
function findHeader(name, headers) {
|
||||
name = name.toLowerCase();
|
||||
for (var header in headers) {
|
||||
if (header.toLowerCase() === name) {
|
||||
return headers[header];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHeaders(rawHeaders, contentType) {
|
||||
var headers = [];
|
||||
|
||||
if (rawHeaders) {
|
||||
if (rawHeaders instanceof Array) {
|
||||
headers = rawHeaders;
|
||||
} else {
|
||||
for (var headerName in rawHeaders) {
|
||||
if (rawHeaders.hasOwnProperty(headerName)) {
|
||||
headers.push({ name: headerName, value: rawHeaders[headerName] });
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
headers.push({ name: "Content-Type", value: contentType || "application/json" });
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
function parseXml(xmlText, contentType) {
|
||||
if (global.DOMParser) {
|
||||
return (new global.DOMParser()).parseFromString(xmlText, 'text/xml');
|
||||
} else {
|
||||
var xml = new global.ActiveXObject("Microsoft.XMLDOM");
|
||||
xml.async = "false";
|
||||
xml.loadXML(xmlText);
|
||||
return xml;
|
||||
}
|
||||
}
|
||||
|
||||
var xmlParsables = ['text/xml', 'application/xml'];
|
||||
|
||||
function getResponseXml(responseText, contentType) {
|
||||
if (arrayContains(xmlParsables, contentType.toLowerCase())) {
|
||||
return parseXml(responseText, contentType);
|
||||
} else if (contentType.match(/\+xml$/)) {
|
||||
return parseXml(responseText, 'text/xml');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout'];
|
||||
extend(FakeXMLHttpRequest.prototype, new global.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
|
||||
extend(FakeXMLHttpRequest.prototype, {
|
||||
open: function() {
|
||||
this.method = arguments[0];
|
||||
this.url = arguments[1];
|
||||
this.username = arguments[3];
|
||||
this.password = arguments[4];
|
||||
this.readyState = 1;
|
||||
this.onreadystatechange();
|
||||
},
|
||||
|
||||
setRequestHeader: function(header, value) {
|
||||
if(this.requestHeaders.hasOwnProperty(header)) {
|
||||
this.requestHeaders[header] = [this.requestHeaders[header], value].join(', ');
|
||||
} else {
|
||||
this.requestHeaders[header] = value;
|
||||
}
|
||||
},
|
||||
|
||||
overrideMimeType: function(mime) {
|
||||
this.overriddenMimeType = mime;
|
||||
},
|
||||
|
||||
abort: function() {
|
||||
this.readyState = 0;
|
||||
this.status = 0;
|
||||
this.statusText = "abort";
|
||||
this.onreadystatechange();
|
||||
this.events.progress();
|
||||
this.events.abort();
|
||||
this.events.loadend();
|
||||
},
|
||||
|
||||
readyState: 0,
|
||||
|
||||
onloadstart: null,
|
||||
onprogress: null,
|
||||
onabort: null,
|
||||
onerror: null,
|
||||
onload: null,
|
||||
ontimeout: null,
|
||||
onloadend: null,
|
||||
|
||||
onreadystatechange: function(isTimeout) {
|
||||
},
|
||||
|
||||
addEventListener: function(event, callback) {
|
||||
var existingCallback = this.events[event],
|
||||
self = this;
|
||||
|
||||
this.events[event] = function() {
|
||||
callback.apply(self);
|
||||
existingCallback();
|
||||
};
|
||||
},
|
||||
|
||||
status: null,
|
||||
|
||||
send: function(data) {
|
||||
this.params = data;
|
||||
this.readyState = 2;
|
||||
this.events.loadstart();
|
||||
this.onreadystatechange();
|
||||
|
||||
var stub = stubTracker.findStub(this.url, data, this.method);
|
||||
if (stub) {
|
||||
this.respondWith(stub);
|
||||
}
|
||||
},
|
||||
|
||||
contentType: function() {
|
||||
return findHeader('content-type', this.requestHeaders);
|
||||
},
|
||||
|
||||
data: function() {
|
||||
if (!this.params) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return paramParser.findParser(this).parse(this.params);
|
||||
},
|
||||
|
||||
getResponseHeader: function(name) {
|
||||
name = name.toLowerCase();
|
||||
var resultHeader;
|
||||
for(var i = 0; i < this.responseHeaders.length; i++) {
|
||||
var header = this.responseHeaders[i];
|
||||
if (name === header.name.toLowerCase()) {
|
||||
if (resultHeader) {
|
||||
resultHeader = [resultHeader, header.value].join(', ');
|
||||
} else {
|
||||
resultHeader = header.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
return resultHeader;
|
||||
},
|
||||
|
||||
getAllResponseHeaders: function() {
|
||||
var responseHeaders = [];
|
||||
for (var i = 0; i < this.responseHeaders.length; i++) {
|
||||
responseHeaders.push(this.responseHeaders[i].name + ': ' +
|
||||
this.responseHeaders[i].value);
|
||||
}
|
||||
return responseHeaders.join('\r\n');
|
||||
},
|
||||
|
||||
responseText: null,
|
||||
response: null,
|
||||
responseType: null,
|
||||
|
||||
responseValue: function() {
|
||||
switch(this.responseType) {
|
||||
case null:
|
||||
case "":
|
||||
case "text":
|
||||
return this.readyState >= 3 ? this.responseText : "";
|
||||
case "json":
|
||||
return JSON.parse(this.responseText);
|
||||
case "arraybuffer":
|
||||
throw unconvertibleResponseTypeMessage('arraybuffer');
|
||||
case "blob":
|
||||
throw unconvertibleResponseTypeMessage('blob');
|
||||
case "document":
|
||||
return this.responseXML;
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
respondWith: function(response) {
|
||||
if (this.readyState === 4) {
|
||||
throw new Error("FakeXMLHttpRequest already completed");
|
||||
}
|
||||
this.status = response.status;
|
||||
this.statusText = response.statusText || "";
|
||||
this.responseText = response.responseText || "";
|
||||
this.responseType = response.responseType || "";
|
||||
this.readyState = 4;
|
||||
this.responseHeaders = normalizeHeaders(response.responseHeaders, response.contentType);
|
||||
this.responseXML = getResponseXml(response.responseText, this.getResponseHeader('content-type') || '');
|
||||
if (this.responseXML) {
|
||||
this.responseType = 'document';
|
||||
}
|
||||
|
||||
if ('response' in response) {
|
||||
this.response = response.response;
|
||||
} else {
|
||||
this.response = this.responseValue();
|
||||
}
|
||||
|
||||
this.onreadystatechange();
|
||||
this.events.progress();
|
||||
this.events.load();
|
||||
this.events.loadend();
|
||||
},
|
||||
|
||||
responseTimeout: function() {
|
||||
if (this.readyState === 4) {
|
||||
throw new Error("FakeXMLHttpRequest already completed");
|
||||
}
|
||||
this.readyState = 4;
|
||||
jasmine.clock().tick(30000);
|
||||
this.onreadystatechange('timeout');
|
||||
this.events.progress();
|
||||
this.events.timeout();
|
||||
this.events.loadend();
|
||||
},
|
||||
|
||||
responseError: function() {
|
||||
if (this.readyState === 4) {
|
||||
throw new Error("FakeXMLHttpRequest already completed");
|
||||
}
|
||||
this.readyState = 4;
|
||||
this.onreadystatechange();
|
||||
this.events.progress();
|
||||
this.events.error();
|
||||
this.events.loadend();
|
||||
}
|
||||
});
|
||||
|
||||
return FakeXMLHttpRequest;
|
||||
}
|
||||
|
||||
return fakeRequest;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().MockAjax = function($ajax) {
|
||||
function MockAjax(global) {
|
||||
var requestTracker = new $ajax.RequestTracker(),
|
||||
stubTracker = new $ajax.StubTracker(),
|
||||
paramParser = new $ajax.ParamParser(),
|
||||
realAjaxFunction = global.XMLHttpRequest,
|
||||
mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser);
|
||||
|
||||
this.install = function() {
|
||||
global.XMLHttpRequest = mockAjaxFunction;
|
||||
};
|
||||
|
||||
this.uninstall = function() {
|
||||
global.XMLHttpRequest = realAjaxFunction;
|
||||
|
||||
this.stubs.reset();
|
||||
this.requests.reset();
|
||||
paramParser.reset();
|
||||
};
|
||||
|
||||
this.stubRequest = function(url, data, method) {
|
||||
var stub = new $ajax.RequestStub(url, data, method);
|
||||
stubTracker.addStub(stub);
|
||||
return stub;
|
||||
};
|
||||
|
||||
this.withMock = function(closure) {
|
||||
this.install();
|
||||
try {
|
||||
closure();
|
||||
} finally {
|
||||
this.uninstall();
|
||||
}
|
||||
};
|
||||
|
||||
this.addCustomParamParser = function(parser) {
|
||||
paramParser.add(parser);
|
||||
};
|
||||
|
||||
this.requests = requestTracker;
|
||||
this.stubs = stubTracker;
|
||||
}
|
||||
|
||||
return MockAjax;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().AjaxParamParser = function() {
|
||||
function ParamParser() {
|
||||
var defaults = [
|
||||
{
|
||||
test: function(xhr) {
|
||||
return (/^application\/json/).test(xhr.contentType());
|
||||
},
|
||||
parse: function jsonParser(paramString) {
|
||||
return JSON.parse(paramString);
|
||||
}
|
||||
},
|
||||
{
|
||||
test: function(xhr) {
|
||||
return true;
|
||||
},
|
||||
parse: function naiveParser(paramString) {
|
||||
var data = {};
|
||||
var params = paramString.split('&');
|
||||
|
||||
for (var i = 0; i < params.length; ++i) {
|
||||
var kv = params[i].replace(/\+/g, ' ').split('=');
|
||||
var key = decodeURIComponent(kv[0]);
|
||||
data[key] = data[key] || [];
|
||||
data[key].push(decodeURIComponent(kv[1]));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
];
|
||||
var paramParsers = [];
|
||||
|
||||
this.add = function(parser) {
|
||||
paramParsers.unshift(parser);
|
||||
};
|
||||
|
||||
this.findParser = function(xhr) {
|
||||
for(var i in paramParsers) {
|
||||
var parser = paramParsers[i];
|
||||
if (parser.test(xhr)) {
|
||||
return parser;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.reset = function() {
|
||||
paramParsers = [];
|
||||
for(var i in defaults) {
|
||||
paramParsers.push(defaults[i]);
|
||||
}
|
||||
};
|
||||
|
||||
this.reset();
|
||||
}
|
||||
|
||||
return ParamParser;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().AjaxRequestStub = function() {
|
||||
function RequestStub(url, stubData, method) {
|
||||
var normalizeQuery = function(query) {
|
||||
return query ? query.split('&').sort().join('&') : undefined;
|
||||
};
|
||||
|
||||
if (url instanceof RegExp) {
|
||||
this.url = url;
|
||||
this.query = undefined;
|
||||
} else {
|
||||
var split = url.split('?');
|
||||
this.url = split[0];
|
||||
this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined;
|
||||
}
|
||||
|
||||
this.data = normalizeQuery(stubData);
|
||||
this.method = method;
|
||||
|
||||
this.andReturn = function(options) {
|
||||
this.status = options.status || 200;
|
||||
|
||||
this.contentType = options.contentType;
|
||||
this.response = options.response;
|
||||
this.responseText = options.responseText;
|
||||
};
|
||||
|
||||
this.matches = function(fullUrl, data, method) {
|
||||
var matches = false;
|
||||
fullUrl = fullUrl.toString();
|
||||
if (this.url instanceof RegExp) {
|
||||
matches = this.url.test(fullUrl);
|
||||
} else {
|
||||
var urlSplit = fullUrl.split('?'),
|
||||
url = urlSplit[0],
|
||||
query = urlSplit[1];
|
||||
matches = this.url === url && this.query === normalizeQuery(query);
|
||||
}
|
||||
return matches && (!this.data || this.data === normalizeQuery(data)) && (!this.method || this.method === method);
|
||||
};
|
||||
}
|
||||
|
||||
return RequestStub;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().AjaxRequestTracker = function() {
|
||||
function RequestTracker() {
|
||||
var requests = [];
|
||||
|
||||
this.track = function(request) {
|
||||
requests.push(request);
|
||||
};
|
||||
|
||||
this.first = function() {
|
||||
return requests[0];
|
||||
};
|
||||
|
||||
this.count = function() {
|
||||
return requests.length;
|
||||
};
|
||||
|
||||
this.reset = function() {
|
||||
requests = [];
|
||||
};
|
||||
|
||||
this.mostRecent = function() {
|
||||
return requests[requests.length - 1];
|
||||
};
|
||||
|
||||
this.at = function(index) {
|
||||
return requests[index];
|
||||
};
|
||||
|
||||
this.filter = function(url_to_match) {
|
||||
var matching_requests = [];
|
||||
|
||||
for (var i = 0; i < requests.length; i++) {
|
||||
if (url_to_match instanceof RegExp &&
|
||||
url_to_match.test(requests[i].url)) {
|
||||
matching_requests.push(requests[i]);
|
||||
} else if (url_to_match instanceof Function &&
|
||||
url_to_match(requests[i])) {
|
||||
matching_requests.push(requests[i]);
|
||||
} else {
|
||||
if (requests[i].url === url_to_match) {
|
||||
matching_requests.push(requests[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matching_requests;
|
||||
};
|
||||
}
|
||||
|
||||
return RequestTracker;
|
||||
};
|
||||
|
||||
getJasmineRequireObj().AjaxStubTracker = function() {
|
||||
function StubTracker() {
|
||||
var stubs = [];
|
||||
|
||||
this.addStub = function(stub) {
|
||||
stubs.push(stub);
|
||||
};
|
||||
|
||||
this.reset = function() {
|
||||
stubs = [];
|
||||
};
|
||||
|
||||
this.findStub = function(url, data, method) {
|
||||
for (var i = stubs.length - 1; i >= 0; i--) {
|
||||
var stub = stubs[i];
|
||||
if (stub.matches(url, data, method)) {
|
||||
return stub;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return StubTracker;
|
||||
};
|
||||
|
||||
(function() {
|
||||
var jRequire = getJasmineRequireObj(),
|
||||
MockAjax = jRequire.ajax(jRequire);
|
||||
if (typeof window === "undefined" && typeof exports === "object") {
|
||||
exports.MockAjax = MockAjax;
|
||||
jasmine.Ajax = new MockAjax(exports);
|
||||
} else {
|
||||
window.MockAjax = MockAjax;
|
||||
jasmine.Ajax = new MockAjax(window);
|
||||
}
|
||||
}());
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
Copyright (c) 2008-2014 Pivotal Labs
|
||||
|
||||
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.
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||||
<title>Jasmine Spec Runner v2.0.3</title>
|
||||
|
||||
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.0.3/jasmine_favicon.png">
|
||||
<link rel="stylesheet" type="text/css" href="lib/jasmine-2.0.3/jasmine.css">
|
||||
|
||||
<script type="text/javascript" src="lib/jasmine-2.0.3/jasmine.js"></script>
|
||||
<script type="text/javascript" src="lib/jasmine-2.0.3/jasmine-html.js"></script>
|
||||
<script type="text/javascript" src="lib/jasmine-2.0.3/boot.js"></script>
|
||||
|
||||
<!-- include source files here... -->
|
||||
<script type="text/javascript" src="src/Player.js"></script>
|
||||
<script type="text/javascript" src="src/Song.js"></script>
|
||||
|
||||
<!-- include spec files here... -->
|
||||
<script type="text/javascript" src="spec/SpecHelper.js"></script>
|
||||
<script type="text/javascript" src="spec/PlayerSpec.js"></script>
|
||||
|
||||
</head>
|
||||
|
||||
<body>
|
||||
</body>
|
||||
</html>
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
/**
|
||||
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
|
||||
|
||||
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
|
||||
|
||||
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
|
||||
|
||||
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
|
||||
*/
|
||||
|
||||
(function() {
|
||||
|
||||
/**
|
||||
* ## Require & Instantiate
|
||||
*
|
||||
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
|
||||
*/
|
||||
window.jasmine = jasmineRequire.core(jasmineRequire);
|
||||
|
||||
/**
|
||||
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
|
||||
*/
|
||||
jasmineRequire.html(jasmine);
|
||||
|
||||
/**
|
||||
* Create the Jasmine environment. This is used to run all specs in a project.
|
||||
*/
|
||||
var env = jasmine.getEnv();
|
||||
|
||||
/**
|
||||
* ## The Global Interface
|
||||
*
|
||||
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
|
||||
*/
|
||||
var jasmineInterface = jasmineRequire.interface(jasmine, env);
|
||||
|
||||
/**
|
||||
* Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
|
||||
*/
|
||||
if (typeof window == "undefined" && typeof exports == "object") {
|
||||
extend(exports, jasmineInterface);
|
||||
} else {
|
||||
extend(window, jasmineInterface);
|
||||
}
|
||||
|
||||
/**
|
||||
* ## Runner Parameters
|
||||
*
|
||||
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
|
||||
*/
|
||||
|
||||
var queryString = new jasmine.QueryString({
|
||||
getWindowLocation: function() { return window.location; }
|
||||
});
|
||||
|
||||
var catchingExceptions = queryString.getParam("catch");
|
||||
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
|
||||
|
||||
/**
|
||||
* ## Reporters
|
||||
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
|
||||
*/
|
||||
var htmlReporter = new jasmine.HtmlReporter({
|
||||
env: env,
|
||||
onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
|
||||
getContainer: function() { return document.body; },
|
||||
createElement: function() { return document.createElement.apply(document, arguments); },
|
||||
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
|
||||
timer: new jasmine.Timer()
|
||||
});
|
||||
|
||||
/**
|
||||
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
|
||||
*/
|
||||
env.addReporter(jasmineInterface.jsApiReporter);
|
||||
env.addReporter(htmlReporter);
|
||||
|
||||
/**
|
||||
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
|
||||
*/
|
||||
var specFilter = new jasmine.HtmlSpecFilter({
|
||||
filterString: function() { return queryString.getParam("spec"); }
|
||||
});
|
||||
|
||||
env.specFilter = function(spec) {
|
||||
return specFilter.matches(spec.getFullName());
|
||||
};
|
||||
|
||||
/**
|
||||
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
|
||||
*/
|
||||
window.setTimeout = window.setTimeout;
|
||||
window.setInterval = window.setInterval;
|
||||
window.clearTimeout = window.clearTimeout;
|
||||
window.clearInterval = window.clearInterval;
|
||||
|
||||
/**
|
||||
* ## Execution
|
||||
*
|
||||
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
|
||||
*/
|
||||
var currentWindowOnload = window.onload;
|
||||
|
||||
window.onload = function() {
|
||||
if (currentWindowOnload) {
|
||||
currentWindowOnload();
|
||||
}
|
||||
htmlReporter.initialize();
|
||||
env.execute();
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper function for readability above.
|
||||
*/
|
||||
function extend(destination, source) {
|
||||
for (var property in source) destination[property] = source[property];
|
||||
return destination;
|
||||
}
|
||||
|
||||
}());
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
/*
|
||||
Copyright (c) 2008-2014 Pivotal Labs
|
||||
|
||||
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.
|
||||
*/
|
||||
function getJasmineRequireObj() {
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
return exports;
|
||||
} else {
|
||||
window.jasmineRequire = window.jasmineRequire || {};
|
||||
return window.jasmineRequire;
|
||||
}
|
||||
}
|
||||
|
||||
getJasmineRequireObj().console = function(jRequire, j$) {
|
||||
j$.ConsoleReporter = jRequire.ConsoleReporter();
|
||||
};
|
||||
|
||||
getJasmineRequireObj().ConsoleReporter = function() {
|
||||
|
||||
var noopTimer = {
|
||||
start: function(){},
|
||||
elapsed: function(){ return 0; }
|
||||
};
|
||||
|
||||
function ConsoleReporter(options) {
|
||||
var print = options.print,
|
||||
showColors = options.showColors || false,
|
||||
onComplete = options.onComplete || function() {},
|
||||
timer = options.timer || noopTimer,
|
||||
specCount,
|
||||
failureCount,
|
||||
failedSpecs = [],
|
||||
pendingCount,
|
||||
ansi = {
|
||||
green: '\x1B[32m',
|
||||
red: '\x1B[31m',
|
||||
yellow: '\x1B[33m',
|
||||
none: '\x1B[0m'
|
||||
};
|
||||
|
||||
this.jasmineStarted = function() {
|
||||
specCount = 0;
|
||||
failureCount = 0;
|
||||
pendingCount = 0;
|
||||
print('Started');
|
||||
printNewline();
|
||||
timer.start();
|
||||
};
|
||||
|
||||
this.jasmineDone = function() {
|
||||
printNewline();
|
||||
for (var i = 0; i < failedSpecs.length; i++) {
|
||||
specFailureDetails(failedSpecs[i]);
|
||||
}
|
||||
|
||||
if(specCount > 0) {
|
||||
printNewline();
|
||||
|
||||
var specCounts = specCount + ' ' + plural('spec', specCount) + ', ' +
|
||||
failureCount + ' ' + plural('failure', failureCount);
|
||||
|
||||
if (pendingCount) {
|
||||
specCounts += ', ' + pendingCount + ' pending ' + plural('spec', pendingCount);
|
||||
}
|
||||
|
||||
print(specCounts);
|
||||
} else {
|
||||
print('No specs found');
|
||||
}
|
||||
|
||||
printNewline();
|
||||
var seconds = timer.elapsed() / 1000;
|
||||
print('Finished in ' + seconds + ' ' + plural('second', seconds));
|
||||
|
||||
printNewline();
|
||||
|
||||
onComplete(failureCount === 0);
|
||||
};
|
||||
|
||||
this.specDone = function(result) {
|
||||
specCount++;
|
||||
|
||||
if (result.status == 'pending') {
|
||||
pendingCount++;
|
||||
print(colored('yellow', '*'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status == 'passed') {
|
||||
print(colored('green', '.'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status == 'failed') {
|
||||
failureCount++;
|
||||
failedSpecs.push(result);
|
||||
print(colored('red', 'F'));
|
||||
}
|
||||
};
|
||||
|
||||
return this;
|
||||
|
||||
function printNewline() {
|
||||
print('\n');
|
||||
}
|
||||
|
||||
function colored(color, str) {
|
||||
return showColors ? (ansi[color] + str + ansi.none) : str;
|
||||
}
|
||||
|
||||
function plural(str, count) {
|
||||
return count == 1 ? str : str + 's';
|
||||
}
|
||||
|
||||
function repeat(thing, times) {
|
||||
var arr = [];
|
||||
for (var i = 0; i < times; i++) {
|
||||
arr.push(thing);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
function indent(str, spaces) {
|
||||
var lines = (str || '').split('\n');
|
||||
var newArr = [];
|
||||
for (var i = 0; i < lines.length; i++) {
|
||||
newArr.push(repeat(' ', spaces).join('') + lines[i]);
|
||||
}
|
||||
return newArr.join('\n');
|
||||
}
|
||||
|
||||
function specFailureDetails(result) {
|
||||
printNewline();
|
||||
print(result.fullName);
|
||||
|
||||
for (var i = 0; i < result.failedExpectations.length; i++) {
|
||||
var failedExpectation = result.failedExpectations[i];
|
||||
printNewline();
|
||||
print(indent(failedExpectation.message, 2));
|
||||
print(indent(failedExpectation.stack, 2));
|
||||
}
|
||||
|
||||
printNewline();
|
||||
}
|
||||
}
|
||||
|
||||
return ConsoleReporter;
|
||||
};
|
||||
|
|
@ -0,0 +1,390 @@
|
|||
/*
|
||||
Copyright (c) 2008-2014 Pivotal Labs
|
||||
|
||||
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.
|
||||
*/
|
||||
jasmineRequire.html = function(j$) {
|
||||
j$.ResultsNode = jasmineRequire.ResultsNode();
|
||||
j$.HtmlReporter = jasmineRequire.HtmlReporter(j$);
|
||||
j$.QueryString = jasmineRequire.QueryString();
|
||||
j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter();
|
||||
};
|
||||
|
||||
jasmineRequire.HtmlReporter = function(j$) {
|
||||
|
||||
var noopTimer = {
|
||||
start: function() {},
|
||||
elapsed: function() { return 0; }
|
||||
};
|
||||
|
||||
function HtmlReporter(options) {
|
||||
var env = options.env || {},
|
||||
getContainer = options.getContainer,
|
||||
createElement = options.createElement,
|
||||
createTextNode = options.createTextNode,
|
||||
onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {},
|
||||
timer = options.timer || noopTimer,
|
||||
results = [],
|
||||
specsExecuted = 0,
|
||||
failureCount = 0,
|
||||
pendingSpecCount = 0,
|
||||
htmlReporterMain,
|
||||
symbols;
|
||||
|
||||
this.initialize = function() {
|
||||
clearPrior();
|
||||
htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'},
|
||||
createDom('div', {className: 'banner'},
|
||||
createDom('a', {className: 'title', href: 'http://jasmine.github.io/', target: '_blank'}),
|
||||
createDom('span', {className: 'version'}, j$.version)
|
||||
),
|
||||
createDom('ul', {className: 'symbol-summary'}),
|
||||
createDom('div', {className: 'alert'}),
|
||||
createDom('div', {className: 'results'},
|
||||
createDom('div', {className: 'failures'})
|
||||
)
|
||||
);
|
||||
getContainer().appendChild(htmlReporterMain);
|
||||
|
||||
symbols = find('.symbol-summary');
|
||||
};
|
||||
|
||||
var totalSpecsDefined;
|
||||
this.jasmineStarted = function(options) {
|
||||
totalSpecsDefined = options.totalSpecsDefined || 0;
|
||||
timer.start();
|
||||
};
|
||||
|
||||
var summary = createDom('div', {className: 'summary'});
|
||||
|
||||
var topResults = new j$.ResultsNode({}, '', null),
|
||||
currentParent = topResults;
|
||||
|
||||
this.suiteStarted = function(result) {
|
||||
currentParent.addChild(result, 'suite');
|
||||
currentParent = currentParent.last();
|
||||
};
|
||||
|
||||
this.suiteDone = function(result) {
|
||||
if (currentParent == topResults) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentParent = currentParent.parent;
|
||||
};
|
||||
|
||||
this.specStarted = function(result) {
|
||||
currentParent.addChild(result, 'spec');
|
||||
};
|
||||
|
||||
var failures = [];
|
||||
this.specDone = function(result) {
|
||||
if(noExpectations(result) && console && console.error) {
|
||||
console.error('Spec \'' + result.fullName + '\' has no expectations.');
|
||||
}
|
||||
|
||||
if (result.status != 'disabled') {
|
||||
specsExecuted++;
|
||||
}
|
||||
|
||||
symbols.appendChild(createDom('li', {
|
||||
className: noExpectations(result) ? 'empty' : result.status,
|
||||
id: 'spec_' + result.id,
|
||||
title: result.fullName
|
||||
}
|
||||
));
|
||||
|
||||
if (result.status == 'failed') {
|
||||
failureCount++;
|
||||
|
||||
var failure =
|
||||
createDom('div', {className: 'spec-detail failed'},
|
||||
createDom('div', {className: 'description'},
|
||||
createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName)
|
||||
),
|
||||
createDom('div', {className: 'messages'})
|
||||
);
|
||||
var messages = failure.childNodes[1];
|
||||
|
||||
for (var i = 0; i < result.failedExpectations.length; i++) {
|
||||
var expectation = result.failedExpectations[i];
|
||||
messages.appendChild(createDom('div', {className: 'result-message'}, expectation.message));
|
||||
messages.appendChild(createDom('div', {className: 'stack-trace'}, expectation.stack));
|
||||
}
|
||||
|
||||
failures.push(failure);
|
||||
}
|
||||
|
||||
if (result.status == 'pending') {
|
||||
pendingSpecCount++;
|
||||
}
|
||||
};
|
||||
|
||||
this.jasmineDone = function() {
|
||||
var banner = find('.banner');
|
||||
banner.appendChild(createDom('span', {className: 'duration'}, 'finished in ' + timer.elapsed() / 1000 + 's'));
|
||||
|
||||
var alert = find('.alert');
|
||||
|
||||
alert.appendChild(createDom('span', { className: 'exceptions' },
|
||||
createDom('label', { className: 'label', 'for': 'raise-exceptions' }, 'raise exceptions'),
|
||||
createDom('input', {
|
||||
className: 'raise',
|
||||
id: 'raise-exceptions',
|
||||
type: 'checkbox'
|
||||
})
|
||||
));
|
||||
var checkbox = find('#raise-exceptions');
|
||||
|
||||
checkbox.checked = !env.catchingExceptions();
|
||||
checkbox.onclick = onRaiseExceptionsClick;
|
||||
|
||||
if (specsExecuted < totalSpecsDefined) {
|
||||
var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all';
|
||||
alert.appendChild(
|
||||
createDom('span', {className: 'bar skipped'},
|
||||
createDom('a', {href: '?', title: 'Run all specs'}, skippedMessage)
|
||||
)
|
||||
);
|
||||
}
|
||||
var statusBarMessage = '';
|
||||
var statusBarClassName = 'bar ';
|
||||
|
||||
if (totalSpecsDefined > 0) {
|
||||
statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount);
|
||||
if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); }
|
||||
statusBarClassName += (failureCount > 0) ? 'failed' : 'passed';
|
||||
} else {
|
||||
statusBarClassName += 'skipped';
|
||||
statusBarMessage += 'No specs found';
|
||||
}
|
||||
|
||||
alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage));
|
||||
|
||||
var results = find('.results');
|
||||
results.appendChild(summary);
|
||||
|
||||
summaryList(topResults, summary);
|
||||
|
||||
function summaryList(resultsTree, domParent) {
|
||||
var specListNode;
|
||||
for (var i = 0; i < resultsTree.children.length; i++) {
|
||||
var resultNode = resultsTree.children[i];
|
||||
if (resultNode.type == 'suite') {
|
||||
var suiteListNode = createDom('ul', {className: 'suite', id: 'suite-' + resultNode.result.id},
|
||||
createDom('li', {className: 'suite-detail'},
|
||||
createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description)
|
||||
)
|
||||
);
|
||||
|
||||
summaryList(resultNode, suiteListNode);
|
||||
domParent.appendChild(suiteListNode);
|
||||
}
|
||||
if (resultNode.type == 'spec') {
|
||||
if (domParent.getAttribute('class') != 'specs') {
|
||||
specListNode = createDom('ul', {className: 'specs'});
|
||||
domParent.appendChild(specListNode);
|
||||
}
|
||||
var specDescription = resultNode.result.description;
|
||||
if(noExpectations(resultNode.result)) {
|
||||
specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription;
|
||||
}
|
||||
specListNode.appendChild(
|
||||
createDom('li', {
|
||||
className: resultNode.result.status,
|
||||
id: 'spec-' + resultNode.result.id
|
||||
},
|
||||
createDom('a', {href: specHref(resultNode.result)}, specDescription)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
alert.appendChild(
|
||||
createDom('span', {className: 'menu bar spec-list'},
|
||||
createDom('span', {}, 'Spec List | '),
|
||||
createDom('a', {className: 'failures-menu', href: '#'}, 'Failures')));
|
||||
alert.appendChild(
|
||||
createDom('span', {className: 'menu bar failure-list'},
|
||||
createDom('a', {className: 'spec-list-menu', href: '#'}, 'Spec List'),
|
||||
createDom('span', {}, ' | Failures ')));
|
||||
|
||||
find('.failures-menu').onclick = function() {
|
||||
setMenuModeTo('failure-list');
|
||||
};
|
||||
find('.spec-list-menu').onclick = function() {
|
||||
setMenuModeTo('spec-list');
|
||||
};
|
||||
|
||||
setMenuModeTo('failure-list');
|
||||
|
||||
var failureNode = find('.failures');
|
||||
for (var i = 0; i < failures.length; i++) {
|
||||
failureNode.appendChild(failures[i]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return this;
|
||||
|
||||
function find(selector) {
|
||||
return getContainer().querySelector('.jasmine_html-reporter ' + selector);
|
||||
}
|
||||
|
||||
function clearPrior() {
|
||||
// return the reporter
|
||||
var oldReporter = find('');
|
||||
|
||||
if(oldReporter) {
|
||||
getContainer().removeChild(oldReporter);
|
||||
}
|
||||
}
|
||||
|
||||
function createDom(type, attrs, childrenVarArgs) {
|
||||
var el = createElement(type);
|
||||
|
||||
for (var i = 2; i < arguments.length; i++) {
|
||||
var child = arguments[i];
|
||||
|
||||
if (typeof child === 'string') {
|
||||
el.appendChild(createTextNode(child));
|
||||
} else {
|
||||
if (child) {
|
||||
el.appendChild(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var attr in attrs) {
|
||||
if (attr == 'className') {
|
||||
el[attr] = attrs[attr];
|
||||
} else {
|
||||
el.setAttribute(attr, attrs[attr]);
|
||||
}
|
||||
}
|
||||
|
||||
return el;
|
||||
}
|
||||
|
||||
function pluralize(singular, count) {
|
||||
var word = (count == 1 ? singular : singular + 's');
|
||||
|
||||
return '' + count + ' ' + word;
|
||||
}
|
||||
|
||||
function specHref(result) {
|
||||
return '?spec=' + encodeURIComponent(result.fullName);
|
||||
}
|
||||
|
||||
function setMenuModeTo(mode) {
|
||||
htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode);
|
||||
}
|
||||
|
||||
function noExpectations(result) {
|
||||
return (result.failedExpectations.length + result.passedExpectations.length) === 0 &&
|
||||
result.status === 'passed';
|
||||
}
|
||||
}
|
||||
|
||||
return HtmlReporter;
|
||||
};
|
||||
|
||||
jasmineRequire.HtmlSpecFilter = function() {
|
||||
function HtmlSpecFilter(options) {
|
||||
var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
|
||||
var filterPattern = new RegExp(filterString);
|
||||
|
||||
this.matches = function(specName) {
|
||||
return filterPattern.test(specName);
|
||||
};
|
||||
}
|
||||
|
||||
return HtmlSpecFilter;
|
||||
};
|
||||
|
||||
jasmineRequire.ResultsNode = function() {
|
||||
function ResultsNode(result, type, parent) {
|
||||
this.result = result;
|
||||
this.type = type;
|
||||
this.parent = parent;
|
||||
|
||||
this.children = [];
|
||||
|
||||
this.addChild = function(result, type) {
|
||||
this.children.push(new ResultsNode(result, type, this));
|
||||
};
|
||||
|
||||
this.last = function() {
|
||||
return this.children[this.children.length - 1];
|
||||
};
|
||||
}
|
||||
|
||||
return ResultsNode;
|
||||
};
|
||||
|
||||
jasmineRequire.QueryString = function() {
|
||||
function QueryString(options) {
|
||||
|
||||
this.setParam = function(key, value) {
|
||||
var paramMap = queryStringToParamMap();
|
||||
paramMap[key] = value;
|
||||
options.getWindowLocation().search = toQueryString(paramMap);
|
||||
};
|
||||
|
||||
this.getParam = function(key) {
|
||||
return queryStringToParamMap()[key];
|
||||
};
|
||||
|
||||
return this;
|
||||
|
||||
function toQueryString(paramMap) {
|
||||
var qStrPairs = [];
|
||||
for (var prop in paramMap) {
|
||||
qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]));
|
||||
}
|
||||
return '?' + qStrPairs.join('&');
|
||||
}
|
||||
|
||||
function queryStringToParamMap() {
|
||||
var paramStr = options.getWindowLocation().search.substring(1),
|
||||
params = [],
|
||||
paramMap = {};
|
||||
|
||||
if (paramStr.length > 0) {
|
||||
params = paramStr.split('&');
|
||||
for (var i = 0; i < params.length; i++) {
|
||||
var p = params[i].split('=');
|
||||
var value = decodeURIComponent(p[1]);
|
||||
if (value === 'true' || value === 'false') {
|
||||
value = JSON.parse(value);
|
||||
}
|
||||
paramMap[decodeURIComponent(p[0])] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return paramMap;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return QueryString;
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
|
|
@ -0,0 +1,58 @@
|
|||
describe("Player", function() {
|
||||
var player;
|
||||
var song;
|
||||
|
||||
beforeEach(function() {
|
||||
player = new Player();
|
||||
song = new Song();
|
||||
});
|
||||
|
||||
it("should be able to play a Song", function() {
|
||||
player.play(song);
|
||||
expect(player.currentlyPlayingSong).toEqual(song);
|
||||
|
||||
//demonstrates use of custom matcher
|
||||
expect(player).toBePlaying(song);
|
||||
});
|
||||
|
||||
describe("when song has been paused", function() {
|
||||
beforeEach(function() {
|
||||
player.play(song);
|
||||
player.pause();
|
||||
});
|
||||
|
||||
it("should indicate that the song is currently paused", function() {
|
||||
expect(player.isPlaying).toBeFalsy();
|
||||
|
||||
// demonstrates use of 'not' with a custom matcher
|
||||
expect(player).not.toBePlaying(song);
|
||||
});
|
||||
|
||||
it("should be possible to resume", function() {
|
||||
player.resume();
|
||||
expect(player.isPlaying).toBeTruthy();
|
||||
expect(player.currentlyPlayingSong).toEqual(song);
|
||||
});
|
||||
});
|
||||
|
||||
// demonstrates use of spies to intercept and test method calls
|
||||
it("tells the current song if the user has made it a favorite", function() {
|
||||
spyOn(song, 'persistFavoriteStatus');
|
||||
|
||||
player.play(song);
|
||||
player.makeFavorite();
|
||||
|
||||
expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
//demonstrates use of expected exceptions
|
||||
describe("#resume", function() {
|
||||
it("should throw an exception if song is already playing", function() {
|
||||
player.play(song);
|
||||
|
||||
expect(function() {
|
||||
player.resume();
|
||||
}).toThrowError("song is already playing");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
beforeEach(function () {
|
||||
jasmine.addMatchers({
|
||||
toBePlaying: function () {
|
||||
return {
|
||||
compare: function (actual, expected) {
|
||||
var player = actual;
|
||||
|
||||
return {
|
||||
pass: player.currentlyPlayingSong === expected && player.isPlaying
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
function Player() {
|
||||
}
|
||||
Player.prototype.play = function(song) {
|
||||
this.currentlyPlayingSong = song;
|
||||
this.isPlaying = true;
|
||||
};
|
||||
|
||||
Player.prototype.pause = function() {
|
||||
this.isPlaying = false;
|
||||
};
|
||||
|
||||
Player.prototype.resume = function() {
|
||||
if (this.isPlaying) {
|
||||
throw new Error("song is already playing");
|
||||
}
|
||||
|
||||
this.isPlaying = true;
|
||||
};
|
||||
|
||||
Player.prototype.makeFavorite = function() {
|
||||
this.currentlyPlayingSong.persistFavoriteStatus(true);
|
||||
};
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
function Song() {
|
||||
}
|
||||
|
||||
Song.prototype.persistFavoriteStatus = function(value) {
|
||||
// something complicated
|
||||
throw new Error("not yet implemented");
|
||||
};
|
||||
|
|
@ -0,0 +1,183 @@
|
|||
/**
|
||||
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
|
||||
|
||||
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
|
||||
|
||||
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
|
||||
|
||||
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
|
||||
*/
|
||||
|
||||
(function() {
|
||||
|
||||
/**
|
||||
* ## Require & Instantiate
|
||||
*
|
||||
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
|
||||
*/
|
||||
window.jasmine = jasmineRequire.core(jasmineRequire);
|
||||
|
||||
/**
|
||||
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
|
||||
*/
|
||||
jasmineRequire.html(jasmine);
|
||||
|
||||
/**
|
||||
* Create the Jasmine environment. This is used to run all specs in a project.
|
||||
*/
|
||||
var env = jasmine.getEnv();
|
||||
|
||||
/**
|
||||
* ## The Global Interface
|
||||
*
|
||||
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
|
||||
*/
|
||||
var jasmineInterface = {
|
||||
describe: function(description, specDefinitions) {
|
||||
return env.describe(description, specDefinitions);
|
||||
},
|
||||
|
||||
xdescribe: function(description, specDefinitions) {
|
||||
return env.xdescribe(description, specDefinitions);
|
||||
},
|
||||
|
||||
it: function(desc, func) {
|
||||
return env.it(desc, func);
|
||||
},
|
||||
|
||||
xit: function(desc, func) {
|
||||
return env.xit(desc, func);
|
||||
},
|
||||
|
||||
beforeEach: function(beforeEachFunction) {
|
||||
return env.beforeEach(beforeEachFunction);
|
||||
},
|
||||
|
||||
afterEach: function(afterEachFunction) {
|
||||
return env.afterEach(afterEachFunction);
|
||||
},
|
||||
|
||||
expect: function(actual) {
|
||||
return env.expect(actual);
|
||||
},
|
||||
|
||||
pending: function() {
|
||||
return env.pending();
|
||||
},
|
||||
|
||||
spyOn: function(obj, methodName) {
|
||||
return env.spyOn(obj, methodName);
|
||||
},
|
||||
|
||||
jsApiReporter: new jasmine.JsApiReporter({
|
||||
timer: new jasmine.Timer()
|
||||
})
|
||||
};
|
||||
|
||||
/**
|
||||
* Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
|
||||
*/
|
||||
if (typeof window == "undefined" && typeof exports == "object") {
|
||||
extend(exports, jasmineInterface);
|
||||
} else {
|
||||
extend(window, jasmineInterface);
|
||||
}
|
||||
|
||||
/**
|
||||
* Expose the interface for adding custom equality testers.
|
||||
*/
|
||||
jasmine.addCustomEqualityTester = function(tester) {
|
||||
env.addCustomEqualityTester(tester);
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose the interface for adding custom expectation matchers
|
||||
*/
|
||||
jasmine.addMatchers = function(matchers) {
|
||||
return env.addMatchers(matchers);
|
||||
};
|
||||
|
||||
/**
|
||||
* Expose the mock interface for the JavaScript timeout functions
|
||||
*/
|
||||
jasmine.clock = function() {
|
||||
return env.clock;
|
||||
};
|
||||
|
||||
/**
|
||||
* ## Runner Parameters
|
||||
*
|
||||
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
|
||||
*/
|
||||
|
||||
var queryString = new jasmine.QueryString({
|
||||
getWindowLocation: function() { return window.location; }
|
||||
});
|
||||
|
||||
var catchingExceptions = queryString.getParam("catch");
|
||||
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
|
||||
|
||||
/**
|
||||
* ## Reporters
|
||||
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
|
||||
*/
|
||||
var htmlReporter = new jasmine.HtmlReporter({
|
||||
env: env,
|
||||
onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); },
|
||||
getContainer: function() { return document.body; },
|
||||
createElement: function() { return document.createElement.apply(document, arguments); },
|
||||
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
|
||||
timer: new jasmine.Timer()
|
||||
});
|
||||
|
||||
/**
|
||||
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
|
||||
*/
|
||||
env.addReporter(jasmineInterface.jsApiReporter);
|
||||
var JUnitXmlReporter = jasmineRequire.JUnitXmlReporter()
|
||||
env.addReporter(new JUnitXmlReporter());
|
||||
env.addReporter(htmlReporter);
|
||||
|
||||
/**
|
||||
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
|
||||
*/
|
||||
var specFilter = new jasmine.HtmlSpecFilter({
|
||||
filterString: function() { return queryString.getParam("spec"); }
|
||||
});
|
||||
|
||||
env.specFilter = function(spec) {
|
||||
return specFilter.matches(spec.getFullName());
|
||||
};
|
||||
|
||||
/**
|
||||
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
|
||||
*/
|
||||
window.setTimeout = window.setTimeout;
|
||||
window.setInterval = window.setInterval;
|
||||
window.clearTimeout = window.clearTimeout;
|
||||
window.clearInterval = window.clearInterval;
|
||||
|
||||
/**
|
||||
* ## Execution
|
||||
*
|
||||
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
|
||||
*/
|
||||
var currentWindowOnload = window.onload;
|
||||
|
||||
window.onload = function() {
|
||||
if (currentWindowOnload) {
|
||||
currentWindowOnload();
|
||||
}
|
||||
htmlReporter.initialize();
|
||||
env.execute();
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper function for readability above.
|
||||
*/
|
||||
function extend(destination, source) {
|
||||
for (var property in source) destination[property] = source[property];
|
||||
return destination;
|
||||
}
|
||||
|
||||
}());
|
||||
|
|
@ -0,0 +1,198 @@
|
|||
(function() {
|
||||
"use strict";
|
||||
|
||||
function getJasmineRequireObj() {
|
||||
if (typeof module !== "undefined" && module.exports) {
|
||||
return exports;
|
||||
} else {
|
||||
window.jasmineRequire = window.jasmineRequire || {};
|
||||
return window.jasmineRequire;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof getJasmineRequireObj() == 'undefined') {
|
||||
throw new Error("jasmine 2.0 must be loaded before jasmine-junit");
|
||||
}
|
||||
|
||||
getJasmineRequireObj().JUnitXmlReporter = function() {
|
||||
|
||||
|
||||
function JUnitXmlReporter(options) {
|
||||
var runStartTime;
|
||||
var specStartTime;
|
||||
var suiteLevel = -1;
|
||||
var suites = []
|
||||
var currentSuite;
|
||||
var totalNumberOfSpecs;
|
||||
var totalNumberOfFailures;
|
||||
|
||||
this.jasmineStarted = function(started) {
|
||||
totalNumberOfSpecs = started.totalSpecsDefined;
|
||||
runStartTime = new Date();
|
||||
};
|
||||
|
||||
this.jasmineDone = function() {
|
||||
console.log('Jasmine ran in ', elapsed(runStartTime, new Date()), ' seconds')
|
||||
window.done = true
|
||||
};
|
||||
|
||||
this.suiteStarted = function(result) {
|
||||
suiteLevel++;
|
||||
if (suiteLevel == 0) {
|
||||
totalNumberOfSpecs = 0;
|
||||
totalNumberOfFailures = 0;
|
||||
suites.push(result);
|
||||
currentSuite = result;
|
||||
currentSuite.startTime = new Date();
|
||||
currentSuite.noOfSpecs = 0;
|
||||
currentSuite.noOfFails = 0;
|
||||
currentSuite.specs = [];
|
||||
}
|
||||
};
|
||||
|
||||
this.suiteDone = function(result) {
|
||||
if (suiteLevel == 0) {
|
||||
currentSuite.endTime = new Date();
|
||||
writeFile('.', descToFilename(result.description), suiteToJUnitXml(currentSuite))
|
||||
}
|
||||
suiteLevel--;
|
||||
};
|
||||
|
||||
this.specStarted = function(result) {
|
||||
specStartTime = new Date();
|
||||
};
|
||||
|
||||
this.specDone = function(result) {
|
||||
totalNumberOfSpecs++;
|
||||
|
||||
if (isFailed(result)) {
|
||||
currentSuite.noOfFails++;
|
||||
}
|
||||
result.startTime = specStartTime;
|
||||
result.endTime = new Date();
|
||||
currentSuite.specs.push(result);
|
||||
currentSuite.noOfSpecs++;
|
||||
};
|
||||
|
||||
return this;
|
||||
|
||||
}
|
||||
|
||||
return JUnitXmlReporter;
|
||||
};
|
||||
|
||||
function isFailed(result) {
|
||||
return result.status === 'failed'
|
||||
}
|
||||
|
||||
function isSkipped(result) {
|
||||
return result.status === 'pending'
|
||||
}
|
||||
|
||||
function suiteToJUnitXml(suite) {
|
||||
var resultXml = '<?xml version="1.0" encoding="UTF-8"?>\n';
|
||||
resultXml += '<testsuites>\n';
|
||||
resultXml += '\t<testsuite tests="' + suite.noOfSpecs + '" errors="0" failures="' + suite.noOfFails + '" time="' + elapsed(suite.startTime, suite.endTime) + '" timestamp="' + ISODateString(suite.startTime) + '">\n'
|
||||
for (var i = 0; i < suite.specs.length; i++) {
|
||||
resultXml += specToJUnitXml(suite.specs[i], suite.id);
|
||||
}
|
||||
resultXml += '\t</testsuite>\n</testsuites>\n\n'
|
||||
return resultXml;
|
||||
}
|
||||
|
||||
function specToJUnitXml(spec, suiteId) {
|
||||
var xml = '\t\t<testcase classname="' + suiteId +
|
||||
'" name="' + escapeInvalidXmlChars(spec.description) + '" time="' + elapsed(spec.startTime, spec.endTime) + '">\n';
|
||||
if (isSkipped(spec)) {
|
||||
xml += '\t\t\t<skipped />\n';
|
||||
}
|
||||
if (isFailed(spec)) {
|
||||
xml += failedToJUnitXml(spec.failedExpectations)
|
||||
}
|
||||
xml += '\t\t</testcase>\n'
|
||||
return xml;
|
||||
}
|
||||
|
||||
function failedToJUnitXml(failedExpectations) {
|
||||
var failure;
|
||||
var failureXml = ""
|
||||
for (var i = 0; i < failedExpectations.length; i++) {
|
||||
failure = failedExpectations[i];
|
||||
failureXml += '\t\t\t<failure type="' + failure.matcherName + '" message="' + trim(escapeInvalidXmlChars(failure.message)) + '">\n';
|
||||
failureXml += escapeInvalidXmlChars(failure.stack || failure.message);
|
||||
failureXml += "\t\t\t</failure>\n";
|
||||
}
|
||||
|
||||
return failureXml;
|
||||
}
|
||||
|
||||
function descToFilename(desc) {
|
||||
return 'TEST-' + desc + '.xml';
|
||||
}
|
||||
|
||||
function ISODateString(d) {
|
||||
function pad(n) {
|
||||
return n < 10 ? '0' + n : n;
|
||||
}
|
||||
|
||||
return d.getFullYear() + '-' +
|
||||
pad(d.getMonth() + 1) + '-' +
|
||||
pad(d.getDate()) + 'T' +
|
||||
pad(d.getHours()) + ':' +
|
||||
pad(d.getMinutes()) + ':' +
|
||||
pad(d.getSeconds());
|
||||
}
|
||||
|
||||
function elapsed(startTime, endTime) {
|
||||
return (endTime - startTime) / 1000;
|
||||
}
|
||||
|
||||
function trim(str) {
|
||||
return str.replace(/^\s+/, "").replace(/\s+$/, "");
|
||||
}
|
||||
|
||||
function escapeInvalidXmlChars(str) {
|
||||
return str.replace(/</g, "<")
|
||||
.replace(/\>/g, ">")
|
||||
.replace(/\"/g, """)
|
||||
.replace(/\'/g, "'")
|
||||
.replace(/\&/g, "&");
|
||||
}
|
||||
|
||||
function writeFile(path, filename, text) {
|
||||
function getQualifiedFilename(separator) {
|
||||
if (path && path.substr(-1) !== separator && filename.substr(0) !== separator) {
|
||||
path += separator;
|
||||
}
|
||||
return path + filename;
|
||||
}
|
||||
|
||||
// PhantomJS
|
||||
if(typeof(__phantom_writeFile) !== 'undefined') {
|
||||
try {
|
||||
// turn filename into a qualified path
|
||||
filename = getQualifiedFilename(window.fs_path_separator);
|
||||
// function injected by jasmine-runner.js
|
||||
__phantom_writeFile(filename, text);
|
||||
return;
|
||||
} catch (error) {
|
||||
console.log('Error writing file', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Node.js
|
||||
if(typeof(global) !== 'undefined') {
|
||||
try {
|
||||
var fs = require("fs");
|
||||
var nodejs_path = require("path");
|
||||
var fd = fs.openSync(nodejs_path.join(path, filename), "w");
|
||||
fs.writeSync(fd, text, 0);
|
||||
fs.closeSync(fd);
|
||||
return;
|
||||
} catch (error) {
|
||||
console.log('Error writing file', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
})()
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,27 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Jasmine Test Runner</title>
|
||||
<link rel="shortcut icon" type="image/png" href="jasmine/lib/jasmine-2.0.3/jasmine_favicon.png">
|
||||
<link rel="stylesheet" type="text/css" href="jasmine/lib/jasmine-2.0.3/jasmine.css">
|
||||
|
||||
<script>document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script>
|
||||
|
||||
<script type="text/javascript" src="jasmine/lib/jasmine-2.0.3/jasmine.js"></script>
|
||||
<script type="text/javascript" src="jasmine/lib/jasmine-2.0.3/jasmine-html.js"></script>
|
||||
<script type="text/javascript" src="jasmine/lib/jasmine-2.0.3/boot.js"></script>
|
||||
<script type="text/javascript" src="jasmine/lib/jasmine-2.0.3/console.js"></script>
|
||||
<script type="text/javascript" src="jasmine-ajax/mock-ajax.js"></script>
|
||||
|
||||
<script type="text/javascript" src="react-and-addons.js"></script>
|
||||
<script type="text/javascript" src="JSXTransformer.js"></script>
|
||||
<script>
|
||||
window.TestUtils = React.addons.TestUtils;
|
||||
</script>
|
||||
<script type="text/javascript" src="specs.js"></script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
28
package.json
28
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "formsy-react",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "A form input builder and validator for React JS",
|
||||
"main": "src/main.js",
|
||||
"scripts": {
|
||||
|
|
@ -9,17 +9,23 @@
|
|||
"author": "Christian Alfoni",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"browserify": "^5.11.2",
|
||||
"gulp": "^3.8.8",
|
||||
"browserify": "^6.2.0",
|
||||
"glob": "^4.0.6",
|
||||
"gulp": "^3.8.9",
|
||||
"gulp-if": "^1.2.4",
|
||||
"gulp-notify": "^1.6.0",
|
||||
"gulp-shell": "^0.2.9",
|
||||
"gulp-jasmine2-phantomjs": "^0.1.1",
|
||||
"gulp-livereload": "^3.4.0",
|
||||
"gulp-notify": "^1.4.2",
|
||||
"gulp-shell": "^0.2.10",
|
||||
"gulp-streamify": "0.0.5",
|
||||
"gulp-uglify": "^1.0.1",
|
||||
"gulp-util": "^3.0.1",
|
||||
"react": "^0.11.2",
|
||||
"reactify": "^0.14.0",
|
||||
"vinyl-source-stream": "^1.0.0",
|
||||
"watchify": "^1.0.2"
|
||||
"gulp-uglify": "^0.3.1",
|
||||
"gulp-util": "^3.0.0",
|
||||
"phantomjs": "^1.9.12",
|
||||
"reactify": "^0.15.2",
|
||||
"vinyl-source-stream": "^0.1.1",
|
||||
"watchify": "^2.1.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^0.12.2"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define(["react"],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Formsy=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
|
||||
(function (global){
|
||||
var React = global.React || require('react');
|
||||
var Formsy = {};
|
||||
|
|
@ -169,10 +169,10 @@ Formsy.Mixin = {
|
|||
return this.state._isPristine;
|
||||
},
|
||||
isRequired: function () {
|
||||
return this.props.required;
|
||||
return !!this.props.required;
|
||||
},
|
||||
showRequired: function () {
|
||||
return this.props.required && this.state._value === '';
|
||||
return this.isRequired() && this.state._value === '';
|
||||
},
|
||||
showError: function () {
|
||||
return !this.showRequired() && !this.state._isValid;
|
||||
|
|
@ -183,7 +183,7 @@ Formsy.addValidationRule = function (name, func) {
|
|||
validationRules[name] = func;
|
||||
};
|
||||
|
||||
Formsy.Form = React.createClass({
|
||||
Formsy.Form = React.createClass({displayName: "Form",
|
||||
getInitialState: function () {
|
||||
return {
|
||||
isValid: true,
|
||||
|
|
@ -228,7 +228,7 @@ Formsy.Form = React.createClass({
|
|||
// if wanting to reset the entire form to original state, the second param is a callback for this.
|
||||
if (!this.props.url) {
|
||||
this.updateModel();
|
||||
this.props.onSubmit(this.model, this.resetModel, this.updateInputsWithError);
|
||||
this.props.onSubmit(this.mapModel(), this.resetModel, this.updateInputsWithError);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -237,11 +237,12 @@ Formsy.Form = React.createClass({
|
|||
isSubmitting: true
|
||||
});
|
||||
|
||||
this.props.onSubmit();
|
||||
this.props.onSubmit(this.mapModel(), this.resetModel, this.updateInputsWithError);
|
||||
|
||||
var headers = (Object.keys(this.props.headers).length && this.props.headers) || options.headers || {};
|
||||
|
||||
ajax[this.props.method || 'post'](this.props.url, this.model, this.props.contentType || options.contentType || 'json', headers)
|
||||
var method = this.props.method && ajax[this.props.method.toLowerCase()] ? this.props.method.toLowerCase() : 'post';
|
||||
ajax[method](this.props.url, this.mapModel(), this.props.contentType || options.contentType || 'json', headers)
|
||||
.then(function (response) {
|
||||
this.props.onSuccess(response);
|
||||
this.props.onSubmitted();
|
||||
|
|
@ -249,6 +250,10 @@ Formsy.Form = React.createClass({
|
|||
.catch(this.failSubmit);
|
||||
},
|
||||
|
||||
mapModel: function () {
|
||||
return this.props.mapping ? this.props.mapping(this.model) : this.model;
|
||||
},
|
||||
|
||||
// Goes through all registered components and
|
||||
// updates the model values
|
||||
updateModel: function () {
|
||||
|
|
@ -451,5 +456,4 @@ if (!global.exports && !global.module && (!global.define || !global.define.amd))
|
|||
module.exports = Formsy;
|
||||
|
||||
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
|
||||
},{"react":"react"}]},{},[1])(1)
|
||||
});
|
||||
},{"react":"react"}]},{},[1]);
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,277 @@
|
|||
var Formsy = require('./../src/main.js');
|
||||
|
||||
describe('Element', function() {
|
||||
|
||||
it('should return passed and setValue() value when using getValue()', function () {
|
||||
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form>
|
||||
<TestInput name="foo" value="foo"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
expect(input.getDOMNode().value).toBe('foo');
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foobar'}});
|
||||
expect(input.getDOMNode().value).toBe('foobar');
|
||||
|
||||
});
|
||||
|
||||
it('should return true or false when calling hasValue() depending on value existance', function () {
|
||||
|
||||
var reset = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
reset = this.resetValue;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form>
|
||||
<TestInput name="foo" value="foo"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
reset();
|
||||
expect(input.getDOMNode().value).toBe('');
|
||||
|
||||
});
|
||||
|
||||
it('should return error message passed when calling getErrorMessage()', function () {
|
||||
|
||||
var getErrorMessage = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
getErrorMessage = this.getErrorMessage;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form>
|
||||
<TestInput name="foo" value="foo" validations="isEmail" validationError="Has to be email"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(getErrorMessage()).toBe('Has to be email');
|
||||
|
||||
});
|
||||
|
||||
it('should return server error message when calling getErrorMessage()', function (done) {
|
||||
|
||||
jasmine.Ajax.install();
|
||||
|
||||
var getErrorMessage = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
getErrorMessage = this.getErrorMessage;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="foo" value="foo" validations="isEmail" validationError="Has to be email"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var form = TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
jasmine.Ajax.requests.mostRecent().respondWith({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
responseText: '{"foo": "bar"}'
|
||||
})
|
||||
|
||||
setTimeout(function () {
|
||||
expect(getErrorMessage()).toBe('bar');
|
||||
jasmine.Ajax.uninstall();
|
||||
done();
|
||||
}, 0);
|
||||
|
||||
});
|
||||
|
||||
it('should return true or false when calling isValid() depending on valid state', function () {
|
||||
|
||||
var isValid = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
isValid = this.isValid;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
console.log('event.target.value', event.target.value);
|
||||
this.setValue(event.target.value);
|
||||
setTimeout(function () {
|
||||
console.log('this.getValue()', this.getValue());
|
||||
}.bind(this), 100);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="foo" value="foo" validations="isEmail"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(isValid()).toBe(false);
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foo@foo.com'}});
|
||||
expect(isValid()).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
it('should return true or false when calling isRequired() depending on passed required attribute', function () {
|
||||
|
||||
var isRequireds = [];
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
isRequireds.push(this.isRequired);
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="foo" value="foo"/>
|
||||
<TestInput name="foo" value="foo" required/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(isRequireds[0]()).toBe(false);
|
||||
expect(isRequireds[1]()).toBe(true);
|
||||
|
||||
});
|
||||
|
||||
it('should return true or false when calling showRequired() depending on input being empty and required is passed, or not', function () {
|
||||
|
||||
var showRequireds = [];
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
showRequireds.push(this.showRequired);
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="A" value="foo"/>
|
||||
<TestInput name="B" value="" required/>
|
||||
<TestInput name="C" value=""/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(showRequireds[0]()).toBe(false);
|
||||
expect(showRequireds[1]()).toBe(true);
|
||||
expect(showRequireds[2]()).toBe(false);
|
||||
|
||||
});
|
||||
|
||||
it('should return true or false when calling showError() depending on value is invalid or a server error has arrived, or not', function (done) {
|
||||
|
||||
var showError = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
showError = this.showError;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="foo" value="foo" validations="isEmail" validationError="This is not an email"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(showError()).toBe(true);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foo@foo.com'}});
|
||||
expect(showError()).toBe(false);
|
||||
|
||||
jasmine.Ajax.install();
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
jasmine.Ajax.requests.mostRecent().respondWith({
|
||||
status: 500,
|
||||
responseType: 'application/json',
|
||||
responseText: '{"foo": "Email already exists"}'
|
||||
});
|
||||
setTimeout(function () {
|
||||
expect(showError()).toBe(true);
|
||||
jasmine.Ajax.uninstall();
|
||||
done();
|
||||
}, 0);
|
||||
});
|
||||
|
||||
it('should return true or false when calling isPrestine() depending on input has been "touched" or not', function () {
|
||||
|
||||
var isPristine = null;
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
componentDidMount: function () {
|
||||
isPristine = this.isPristine;
|
||||
},
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
<TestInput name="A" value="foo"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
expect(isPristine()).toBe(true);
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foo'}});
|
||||
expect(isPristine()).toBe(false);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
var Formsy = require('./../src/main.js');
|
||||
|
||||
describe('Formsy', function() {
|
||||
|
||||
describe('Setting up a form', function () {
|
||||
|
||||
it('should render a form into the document', function() {
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form></Formsy.Form>
|
||||
);
|
||||
expect(form.getDOMNode().tagName).toEqual('FORM');
|
||||
});
|
||||
|
||||
it('should set a class name if passed', function () {
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form className="foo"></Formsy.Form>
|
||||
);
|
||||
expect(form.getDOMNode().className).toEqual('foo');
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
var Formsy = require('./../src/main.js');
|
||||
|
||||
describe('Ajax', function() {
|
||||
|
||||
beforeEach(function () {
|
||||
jasmine.Ajax.install();
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
jasmine.Ajax.uninstall();
|
||||
});
|
||||
|
||||
it('should post to a given url if passed', function () {
|
||||
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users">
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
expect(jasmine.Ajax.requests.mostRecent().url).toBe('/users');
|
||||
expect(jasmine.Ajax.requests.mostRecent().method).toBe('POST');
|
||||
|
||||
});
|
||||
|
||||
it('should put to a given url if passed a method attribute', function () {
|
||||
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" method="PUT">
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
expect(jasmine.Ajax.requests.mostRecent().url).toBe('/users');
|
||||
expect(jasmine.Ajax.requests.mostRecent().method).toBe('PUT');
|
||||
|
||||
});
|
||||
|
||||
it('should pass x-www-form-urlencoded as contentType when urlencoded is set as contentType', function () {
|
||||
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" contentType="urlencoded">
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
expect(jasmine.Ajax.requests.mostRecent().contentType()).toBe('application/x-www-form-urlencoded');
|
||||
|
||||
});
|
||||
|
||||
it('should run an onSuccess handler, if passed and ajax is successfull. First argument is data from server', function (done) {
|
||||
|
||||
var onSuccess = jasmine.createSpy("success");
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" onSuccess={onSuccess}>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
jasmine.Ajax.stubRequest('/users').andReturn({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
responseText: '{}'
|
||||
});
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
// Since ajax is returned as a promise (async), move assertion
|
||||
// to end of event loop
|
||||
setTimeout(function () {
|
||||
expect(onSuccess).toHaveBeenCalledWith({});
|
||||
done();
|
||||
}, 0);
|
||||
|
||||
});
|
||||
|
||||
it('should not do ajax request if onSubmit handler is passed, but pass the model as first argument to onSubmit handler', function () {
|
||||
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
render: function () {
|
||||
return <input value={this.getValue()}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form onSubmit={onSubmit}>
|
||||
<TestInput name="foo" value="bar"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
expect(jasmine.Ajax.requests.count()).toBe(0);
|
||||
|
||||
function onSubmit (data) {
|
||||
expect(data).toEqual({
|
||||
foo: 'bar'
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
it('should trigger an onSubmitted handler, if passed and the submit has responded with SUCCESS', function (done) {
|
||||
|
||||
var onSubmitted = jasmine.createSpy("submitted");
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" onSubmitted={onSubmitted}>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
jasmine.Ajax.stubRequest('/users').andReturn({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
responseText: '{}'
|
||||
});
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
// Since ajax is returned as a promise (async), move assertion
|
||||
// to end of event loop
|
||||
setTimeout(function () {
|
||||
expect(onSubmitted).toHaveBeenCalled();
|
||||
done();
|
||||
}, 0);
|
||||
|
||||
});
|
||||
|
||||
it('should trigger an onSubmitted handler, if passed and the submit has responded with ERROR', function (done) {
|
||||
|
||||
var onSubmitted = jasmine.createSpy("submitted");
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" onSubmitted={onSubmitted}>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
jasmine.Ajax.stubRequest('/users').andReturn({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
responseText: '{}'
|
||||
});
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
// Since ajax is returned as a promise (async), move assertion
|
||||
// to end of event loop
|
||||
setTimeout(function () {
|
||||
expect(onSubmitted).toHaveBeenCalled();
|
||||
done();
|
||||
}, 0);
|
||||
|
||||
});
|
||||
|
||||
it('should trigger an onError handler, if passed and the submit has responded with ERROR', function (done) {
|
||||
|
||||
var onError = jasmine.createSpy("error");
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form url="/users" onError={onError}>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
// Do not return any error because there are no inputs
|
||||
jasmine.Ajax.stubRequest('/users').andReturn({
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
responseText: '{}'
|
||||
});
|
||||
|
||||
TestUtils.Simulate.submit(form.getDOMNode());
|
||||
|
||||
// Since ajax is returned as a promise (async), move assertion
|
||||
// to end of event loop
|
||||
setTimeout(function () {
|
||||
expect(onError).toHaveBeenCalledWith({});
|
||||
done();
|
||||
}, 0);
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
|
|
@ -0,0 +1,81 @@
|
|||
var Formsy = require('./../src/main.js');
|
||||
|
||||
describe('Validation', function() {
|
||||
|
||||
it('should trigger an onValid handler, if passed, when form is valid', function () {
|
||||
|
||||
var onValid = jasmine.createSpy('valid');
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form onValid={onValid}>
|
||||
<TestInput name="foo" required/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foo'}});
|
||||
expect(onValid).toHaveBeenCalled();
|
||||
|
||||
});
|
||||
|
||||
it('should trigger an onInvalid handler, if passed, when form is invalid', function () {
|
||||
|
||||
var onInvalid = jasmine.createSpy('invalid');
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form onValid={onInvalid}>
|
||||
<TestInput name="foo" value="foo"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
TestUtils.Simulate.change(input, {target: {value: ''}});
|
||||
expect(onInvalid).toHaveBeenCalled();
|
||||
|
||||
});
|
||||
|
||||
it('RULE: isEmail', function () {
|
||||
|
||||
var isValid = jasmine.createSpy('valid');
|
||||
var TestInput = React.createClass({
|
||||
mixins: [Formsy.Mixin],
|
||||
updateValue: function (event) {
|
||||
this.setValue(event.target.value);
|
||||
},
|
||||
render: function () {
|
||||
if (this.isValid()) {
|
||||
isValid();
|
||||
}
|
||||
return <input value={this.getValue()} onChange={this.updateValue}/>
|
||||
}
|
||||
});
|
||||
var form = TestUtils.renderIntoDocument(
|
||||
<Formsy.Form>
|
||||
<TestInput name="foo" value="foo" validations="isEmail"/>
|
||||
</Formsy.Form>
|
||||
);
|
||||
|
||||
var input = TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT');
|
||||
expect(isValid).not.toHaveBeenCalled();
|
||||
TestUtils.Simulate.change(input, {target: {value: 'foo@foo.com'}});
|
||||
expect(isValid).toHaveBeenCalled();
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
18
src/main.js
18
src/main.js
|
|
@ -30,6 +30,9 @@ var validationRules = {
|
|||
},
|
||||
equals: function (value, eql) {
|
||||
return value == eql;
|
||||
},
|
||||
equalsField: function (value, field) {
|
||||
return value === this[field];
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -167,10 +170,10 @@ Formsy.Mixin = {
|
|||
return this.state._isPristine;
|
||||
},
|
||||
isRequired: function () {
|
||||
return this.props.required;
|
||||
return !!this.props.required;
|
||||
},
|
||||
showRequired: function () {
|
||||
return this.props.required && this.state._value === '';
|
||||
return this.isRequired() && this.state._value === '';
|
||||
},
|
||||
showError: function () {
|
||||
return !this.showRequired() && !this.state._isValid;
|
||||
|
|
@ -226,7 +229,7 @@ Formsy.Form = React.createClass({
|
|||
// if wanting to reset the entire form to original state, the second param is a callback for this.
|
||||
if (!this.props.url) {
|
||||
this.updateModel();
|
||||
this.props.onSubmit(this.model, this.resetModel, this.updateInputsWithError);
|
||||
this.props.onSubmit(this.mapModel(), this.resetModel, this.updateInputsWithError);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -235,11 +238,12 @@ Formsy.Form = React.createClass({
|
|||
isSubmitting: true
|
||||
});
|
||||
|
||||
this.props.onSubmit();
|
||||
this.props.onSubmit(this.mapModel(), this.resetModel, this.updateInputsWithError);
|
||||
|
||||
var headers = (Object.keys(this.props.headers).length && this.props.headers) || options.headers || {};
|
||||
|
||||
ajax[this.props.method || 'post'](this.props.url, this.model, this.props.contentType || options.contentType || 'json', headers)
|
||||
var method = this.props.method && ajax[this.props.method.toLowerCase()] ? this.props.method.toLowerCase() : 'post';
|
||||
ajax[method](this.props.url, this.mapModel(), this.props.contentType || options.contentType || 'json', headers)
|
||||
.then(function (response) {
|
||||
this.props.onSuccess(response);
|
||||
this.props.onSubmitted();
|
||||
|
|
@ -247,6 +251,10 @@ Formsy.Form = React.createClass({
|
|||
.catch(this.failSubmit);
|
||||
},
|
||||
|
||||
mapModel: function () {
|
||||
return this.props.mapping ? this.props.mapping(this.model) : this.model;
|
||||
},
|
||||
|
||||
// Goes through all registered components and
|
||||
// updates the model values
|
||||
updateModel: function () {
|
||||
|
|
|
|||
Loading…
Reference in New Issue