Add tests and eslint

This commit is contained in:
Harry Hedger 2015-11-17 09:09:45 -05:00
parent de192e135e
commit d257f8ff52
18 changed files with 5438 additions and 6 deletions

12
.editorconfig Normal file
View file

@ -0,0 +1,12 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

194
.eslintrc Normal file
View file

@ -0,0 +1,194 @@
{
"parser": "babel-eslint",
"plugins": [],
"env": {
"node": true
},
"ecmaFeatures": {},
"rules": {
"no-alert": 0,
"no-array-constructor": 0,
"no-bitwise": 0,
"no-caller": 0,
"no-catch-shadow": 0,
"no-class-assign": 0,
"no-cond-assign": 2,
"no-console": 2,
"no-const-assign": 0,
"no-constant-condition": 2,
"no-continue": 0,
"no-control-regex": 2,
"no-debugger": 2,
"no-delete-var": 2,
"no-div-regex": 0,
"no-dupe-class-members": 0,
"no-dupe-keys": 2,
"no-dupe-args": 2,
"no-duplicate-case": 2,
"no-else-return": 0,
"no-empty": 2,
"no-empty-character-class": 2,
"no-empty-label": 0,
"no-eq-null": 0,
"no-eval": 0,
"no-ex-assign": 2,
"no-extend-native": 0,
"no-extra-bind": 0,
"no-extra-boolean-cast": 2,
"no-extra-parens": 0,
"no-extra-semi": 2,
"no-fallthrough": 2,
"no-floating-decimal": 0,
"no-func-assign": 2,
"no-implicit-coercion": 0,
"no-implied-eval": 0,
"no-inline-comments": 0,
"no-inner-declarations": [2, "functions"],
"no-invalid-regexp": 2,
"no-invalid-this": 0,
"no-irregular-whitespace": 2,
"no-iterator": 0,
"no-label-var": 0,
"no-labels": 0,
"no-lone-blocks": 0,
"no-lonely-if": 0,
"no-loop-func": 0,
"no-mixed-requires": [0, false],
"no-mixed-spaces-and-tabs": [2, false],
"linebreak-style": [0, "unix"],
"no-multi-spaces": 0,
"no-multi-str": 0,
"no-multiple-empty-lines": [0, {"max": 2}],
"no-native-reassign": 0,
"no-negated-in-lhs": 2,
"no-nested-ternary": 0,
"no-new": 0,
"no-new-func": 0,
"no-new-object": 0,
"no-new-require": 0,
"no-new-wrappers": 0,
"no-obj-calls": 2,
"no-octal": 2,
"no-octal-escape": 0,
"no-param-reassign": 0,
"no-path-concat": 0,
"no-plusplus": 0,
"no-process-env": 0,
"no-process-exit": 0,
"no-proto": 0,
"no-redeclare": 2,
"no-regex-spaces": 2,
"no-restricted-modules": 0,
"no-restricted-syntax": 0,
"no-return-assign": 0,
"no-script-url": 0,
"no-self-compare": 0,
"no-sequences": 0,
"no-shadow": 0,
"no-shadow-restricted-names": 0,
"no-spaced-func": 0,
"no-sparse-arrays": 2,
"no-sync": 0,
"no-ternary": 0,
"no-trailing-spaces": 0,
"no-this-before-super": 0,
"no-throw-literal": 0,
"no-undef": 2,
"no-undef-init": 0,
"no-undefined": 0,
"no-unexpected-multiline": 0,
"no-underscore-dangle": 0,
"no-unneeded-ternary": 0,
"no-unreachable": 2,
"no-unused-expressions": 0,
"no-unused-vars": [2, {"vars": "all", "args": "after-used", "varsIgnorePattern": "css"}],
"no-use-before-define": 0,
"no-useless-call": 0,
"no-useless-concat": 0,
"no-void": 0,
"no-var": 0,
"no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start" }],
"no-with": 0,
"array-bracket-spacing": [0, "never"],
"arrow-parens": 0,
"arrow-spacing": 0,
"accessor-pairs": 0,
"block-scoped-var": 0,
"block-spacing": 0,
"brace-style": [0, "1tbs"],
"callback-return": 0,
"camelcase": 0,
"comma-dangle": [2, "never"],
"comma-spacing": 0,
"comma-style": 0,
"complexity": [0, 11],
"computed-property-spacing": [0, "never"],
"consistent-return": 0,
"consistent-this": [0, "that"],
"constructor-super": 0,
"curly": [0, "all"],
"default-case": 0,
"dot-location": 0,
"dot-notation": [0, { "allowKeywords": true }],
"eol-last": 0,
"eqeqeq": 0,
"func-names": 0,
"func-style": [0, "declaration"],
"generator-star-spacing": 0,
"global-require": 0,
"guard-for-in": 0,
"handle-callback-err": 0,
"id-length": 0,
"indent": 0,
"init-declarations": 0,
"jsx-quotes": [1, "prefer-double"],
"key-spacing": [0, { "beforeColon": false, "afterColon": true }],
"lines-around-comment": 0,
"max-depth": [0, 4],
"max-len": [0, 80, 4],
"max-nested-callbacks": [0, 2],
"max-params": [0, 3],
"max-statements": [0, 10],
"new-cap": 0,
"new-parens": 0,
"newline-after-var": 0,
"object-curly-spacing": [0, "never"],
"object-shorthand": 0,
"one-var": [0, "always"],
"operator-assignment": [0, "always"],
"operator-linebreak": 0,
"padded-blocks": 0,
"prefer-arrow-callback": 0,
"prefer-const": 0,
"prefer-spread": 0,
"prefer-reflect": 0,
"prefer-template": 0,
"quote-props": 0,
"quotes": [2, "double"],
"radix": 0,
"id-match": 0,
"require-jsdoc": 0,
"require-yield": 0,
"semi": [2, "always"],
"semi-spacing": [0, {"before": false, "after": true}],
"sort-vars": 0,
"space-after-keywords": [2, "always"],
"space-before-keywords": [0, "always"],
"space-before-blocks": [0, "always"],
"space-before-function-paren": [1, {"anonymous": "always", "named": "never"}],
"space-in-parens": [0, "never"],
"space-infix-ops": 0,
"space-return-throw-case": 0,
"space-unary-ops": [0, { "words": true, "nonwords": false }],
"spaced-comment": 0,
"strict": 0,
"use-isnan": 2,
"valid-jsdoc": 0,
"valid-typeof": 2,
"vars-on-top": 0,
"wrap-iife": 0,
"wrap-regex": 0,
"yoda": [0, "never"]
}
}

21
.zuul.yml Normal file
View file

@ -0,0 +1,21 @@
ui: jasmine2
scripts:
- "dist/tus.js"
- "test/spec/fakeBlob.js"
browsers:
- name: internet explorer
version: 9..latest
- name: firefox
platform: linux
version: 31..latest
- name: chrome
platform: linux
version: 31..latest
- name: safari
version: 5..latest
- name: opera
version: 11..latest
- name: android
version: 4.0..latest
- name: iphone
version: 5.1..8.4

View file

@ -5,13 +5,14 @@
"main": "index.js",
"scripts": {
"build": "npm run build:js && npm run build:css",
"build:js": "browserify js/lib/transloadit-js-client.js -o build/transloadit-js-client.js -t [ babelify ]",
"build:css": "node-sass --include-path scss scss/index.scss build/transloadit-js-client.css",
"watch": "npm run watch:js & npm run watch:css",
"watch:js": "watchify js/lib/transloadit-js-client.js -do build/transloadit-js-client.js",
"test": "./scripts/test",
"build:js": "browserify src/js/lib/transloadit-js-client.js -o build/transloadit-js-client.js -t [ babelify ]",
"build:css": "node-sass --include-path src/scss src/scss/index.scss build/transloadit-js-client.css",
"watch:js": "watchify src/js/lib/transloadit-js-client.js -do build/transloadit-js-client.js",
"watch:css": "nodemon -e scss -x \"npm run build:css\"",
"test": "echo \"Error: no test specified\" && exit 1",
"preview": "npm run watch & http-server ./build -d -o "
"preview": "npm run build & http-server ./build -d -o ",
"lint": "eslint *.js src/js"
},
"repository": {
"type": "git",
@ -26,9 +27,12 @@
"devDependencies": {
"babelify": "^6.4.0",
"browserify": "^12.0.1",
"eslint": "^1.9.0",
"node-sass": "^3.4.2",
"nodemon": "^1.8.1",
"http-server": "^0.8.5",
"phantomjs": "^1.9.18",
"watchify": "^3.6.1",
"http-server": "^0.8.5"
"zuul": "^3.7.2"
}
}

20
scripts/test Normal file
View file

@ -0,0 +1,20 @@
#!/bin/bash
# Move into a known directory
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR/..
npm run phantom-test -s
result=$?
if [ "$result" = 0 ];
then
if [ "${CI}" = "true" ] && [ "${TRAVIS_PULL_REQUEST}" = "false" ];
then
npm run zuul-test -s
result=$?
else
echo "Skipping zuul-test as this is not a master CI branch test run"
fi
fi
exit $result

View file

0
src/scss/index.scss Normal file
View file

32
test/SpecRunner.html Normal file
View file

@ -0,0 +1,32 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.2.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.2.0/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.2.0/jasmine.css">
<script src="lib/jasmine-2.2.0/jasmine.js"></script>
<script src="lib/jasmine-2.2.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.2.0/boot.js"></script>
<script type="text/javascript" src="lib/jasmine-2.2.0/console.js"></script>
<script src="lib/mock-ajax.js"></script>
<script src="lib/jasmine-jsreporter.js"></script>
<!-- include source files here... -->
<script src="../dist/tus.js"></script>
<script>
// Add JSReporter to Jasmine
jasmine.getEnv().addReporter(new jasmine.JSReporter2())
</script>
<!-- include spec files here... -->
<script src="spec/fakeBlob.js"></script>
<script src="spec/upload.js"></script>
</head>
<body>
</body>
</html>

View file

@ -0,0 +1,121 @@
/**
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` and `jasmine_html.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 &amp; 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.navigateWithNewParam("catch", !env.catchingExceptions()); },
addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); },
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;
}
}());

View file

@ -0,0 +1,190 @@
/*
Copyright (c) 2008-2015 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'
},
failedSuites = [];
print('ConsoleReporter is deprecated and will be removed in a future version.');
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();
for(i = 0; i < failedSuites.length; i++) {
suiteFailureDetails(failedSuites[i]);
}
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'));
}
};
this.suiteDone = function(result) {
if (result.failedExpectations && result.failedExpectations.length > 0) {
failureCount++;
failedSuites.push(result);
}
};
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();
}
function suiteFailureDetails(result) {
for (var i = 0; i < result.failedExpectations.length; i++) {
printNewline();
print(colored('red', 'An error was thrown in an afterAll'));
printNewline();
print(colored('red', 'AfterAll ' + result.failedExpectations[i].message));
}
printNewline();
}
}
return ConsoleReporter;
};

View file

@ -0,0 +1,416 @@
/*
Copyright (c) 2008-2015 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() {},
addToExistingQueryString = options.addToExistingQueryString || defaultQueryString,
timer = options.timer || noopTimer,
results = [],
specsExecuted = 0,
failureCount = 0,
pendingSpecCount = 0,
htmlReporterMain,
symbols,
failedSuites = [];
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 (result.status == 'failed') {
failedSuites.push(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) && typeof console !== 'undefined' && typeof console.error !== 'undefined') {
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));
for(i = 0; i < failedSuites.length; i++) {
var failedSuite = failedSuites[i];
for(var j = 0; j < failedSuite.failedExpectations.length; j++) {
var errorBarMessage = 'AfterAll ' + failedSuite.failedExpectations[j].message;
var errorBarClassName = 'bar errored';
alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessage));
}
}
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;
}
if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') {
specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason;
}
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 addToExistingQueryString('spec', result.fullName);
}
function defaultQueryString(key, value) {
return '?' + key + '=' + value;
}
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.navigateWithNewParam = function(key, value) {
options.getWindowLocation().search = this.fullStringWithNewParam(key, value);
};
this.fullStringWithNewParam = function(key, value) {
var paramMap = queryStringToParamMap();
paramMap[key] = value;
return 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

View file

@ -0,0 +1,392 @@
/*
This file is part of the Jasmine JSReporter project from Ivan De Marino.
Copyright (C) 2011-2014 Ivan De Marino <http://ivandemarino.me>
Copyright (C) 2014 Alex Treppass <http://alextreppass.co.uk>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL IVAN DE MARINO BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (jasmine) {
if (!jasmine) {
throw new Error("[Jasmine JSReporter] 'Jasmine' library not found");
}
// ------------------------------------------------------------------------
// Jasmine JSReporter for Jasmine 1.x
// ------------------------------------------------------------------------
/**
* Calculate elapsed time, in Seconds.
* @param startMs Start time in Milliseconds
* @param finishMs Finish time in Milliseconds
* @return Elapsed time in Seconds */
function elapsedSec (startMs, finishMs) {
return (finishMs - startMs) / 1000;
}
/**
* Round an amount to the given number of Digits.
* If no number of digits is given, than '2' is assumed.
* @param amount Amount to round
* @param numOfDecDigits Number of Digits to round to. Default value is '2'.
* @return Rounded amount */
function round (amount, numOfDecDigits) {
numOfDecDigits = numOfDecDigits || 2;
return Math.round(amount * Math.pow(10, numOfDecDigits)) / Math.pow(10, numOfDecDigits);
}
/**
* Create a new array which contains only the failed items.
* @param items Items which will be filtered
* @returns {Array} of failed items */
function failures (items) {
var fs = [], i, v;
for (i = 0; i < items.length; i += 1) {
v = items[i];
if (!v.passed_) {
fs.push(v);
}
}
return fs;
}
/**
* Collect information about a Suite, recursively, and return a JSON result.
* @param suite The Jasmine Suite to get data from
*/
function getSuiteData (suite) {
var suiteData = {
description : suite.description,
durationSec : 0,
specs: [],
suites: [],
passed: true
},
specs = suite.specs(),
suites = suite.suites(),
i, ilen;
// Loop over all the Suite's Specs
for (i = 0, ilen = specs.length; i < ilen; ++i) {
suiteData.specs[i] = {
description : specs[i].description,
durationSec : specs[i].durationSec,
passed : specs[i].results().passedCount === specs[i].results().totalCount,
skipped : specs[i].results().skipped,
passedCount : specs[i].results().passedCount,
failedCount : specs[i].results().failedCount,
totalCount : specs[i].results().totalCount,
failures: failures(specs[i].results().getItems())
};
suiteData.passed = !suiteData.specs[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.specs[i].durationSec;
}
// Loop over all the Suite's sub-Suites
for (i = 0, ilen = suites.length; i < ilen; ++i) {
suiteData.suites[i] = getSuiteData(suites[i]); //< recursive population
suiteData.passed = !suiteData.suites[i].passed ? false : suiteData.passed;
suiteData.durationSec += suiteData.suites[i].durationSec;
}
// Rounding duration numbers to 3 decimal digits
suiteData.durationSec = round(suiteData.durationSec, 4);
return suiteData;
}
var JSReporter = function () {
};
JSReporter.prototype = {
reportRunnerStarting: function (runner) {
// Nothing to do
},
reportSpecStarting: function (spec) {
// Start timing this spec
spec.startedAt = new Date();
},
reportSpecResults: function (spec) {
// Finish timing this spec and calculate duration/delta (in sec)
spec.finishedAt = new Date();
// If the spec was skipped, reportSpecStarting is never called and spec.startedAt is undefined
spec.durationSec = spec.startedAt ? elapsedSec(spec.startedAt.getTime(), spec.finishedAt.getTime()) : 0;
},
reportSuiteResults: function (suite) {
// Nothing to do
},
reportRunnerResults: function (runner) {
var suites = runner.suites(),
i, j, ilen;
// Attach results to the "jasmine" object to make those results easy to scrap/find
jasmine.runnerResults = {
suites: [],
durationSec : 0,
passed : true
};
// Loop over all the Suites
for (i = 0, ilen = suites.length, j = 0; i < ilen; ++i) {
if (suites[i].parentSuite === null) {
jasmine.runnerResults.suites[j] = getSuiteData(suites[i]);
// If 1 suite fails, the whole runner fails
jasmine.runnerResults.passed = !jasmine.runnerResults.suites[j].passed ? false : jasmine.runnerResults.passed;
// Add up all the durations
jasmine.runnerResults.durationSec += jasmine.runnerResults.suites[j].durationSec;
j++;
}
}
// Decorate the 'jasmine' object with getters
jasmine.getJSReport = function () {
if (jasmine.runnerResults) {
return jasmine.runnerResults;
}
return null;
};
jasmine.getJSReportAsString = function () {
return JSON.stringify(jasmine.getJSReport());
};
}
};
// export public
jasmine.JSReporter = JSReporter;
// ------------------------------------------------------------------------
// Jasmine JSReporter for Jasmine 2.0
// ------------------------------------------------------------------------
/*
Simple timer implementation
*/
var Timer = function () {};
Timer.prototype.start = function () {
this.startTime = new Date().getTime();
return this;
};
Timer.prototype.elapsed = function () {
if (this.startTime == null) {
return -1;
}
return new Date().getTime() - this.startTime;
};
/*
Utility methods
*/
var _extend = function (obj1, obj2) {
for (var prop in obj2) {
obj1[prop] = obj2[prop];
}
return obj1;
};
var _clone = function (obj) {
if (obj !== Object(obj)) {
return obj;
}
return _extend({}, obj);
};
jasmine.JSReporter2 = function () {
this.specs = {};
this.suites = {};
this.rootSuites = [];
this.suiteStack = [];
// export methods under jasmine namespace
jasmine.getJSReport = this.getJSReport;
jasmine.getJSReportAsString = this.getJSReportAsString;
};
var JSR = jasmine.JSReporter2.prototype;
// Reporter API methods
// --------------------
JSR.suiteStarted = function (suite) {
suite = this._cacheSuite(suite);
// build up suite tree as we go
suite.specs = [];
suite.suites = [];
suite.passed = true;
suite.parentId = this.suiteStack.slice(this.suiteStack.length -1)[0];
if (suite.parentId) {
this.suites[suite.parentId].suites.push(suite);
} else {
this.rootSuites.push(suite.id);
}
this.suiteStack.push(suite.id);
suite.timer = new Timer().start();
};
JSR.suiteDone = function (suite) {
suite = this._cacheSuite(suite);
suite.duration = suite.timer.elapsed();
suite.durationSec = suite.duration / 1000;
this.suiteStack.pop();
// maintain parent suite state
var parent = this.suites[suite.parentId];
if (parent) {
parent.passed = parent.passed && suite.passed;
}
// keep report representation clean
delete suite.timer;
delete suite.id;
delete suite.parentId;
delete suite.fullName;
};
JSR.specStarted = function (spec) {
spec = this._cacheSpec(spec);
spec.timer = new Timer().start();
// build up suites->spec tree as we go
spec.suiteId = this.suiteStack.slice(this.suiteStack.length -1)[0];
this.suites[spec.suiteId].specs.push(spec);
};
JSR.specDone = function (spec) {
spec = this._cacheSpec(spec);
spec.duration = spec.timer.elapsed();
spec.durationSec = spec.duration / 1000;
spec.skipped = spec.status === 'pending';
spec.passed = spec.skipped || spec.status === 'passed';
spec.totalCount = spec.passedExpectations.length + spec.failedExpectations.length;
spec.passedCount = spec.passedExpectations.length;
spec.failedCount = spec.failedExpectations.length;
spec.failures = [];
for (var i = 0, j = spec.failedExpectations.length; i < j; i++) {
var fail = spec.failedExpectations[i];
spec.failures.push({
type: 'expect',
expected: fail.expected,
passed: false,
message: fail.message,
matcherName: fail.matcherName,
trace: {
stack: fail.stack
}
});
}
// maintain parent suite state
var parent = this.suites[spec.suiteId];
if (spec.failed) {
parent.failingSpecs.push(spec);
}
parent.passed = parent.passed && spec.passed;
// keep report representation clean
delete spec.timer;
delete spec.totalExpectations;
delete spec.passedExpectations;
delete spec.suiteId;
delete spec.fullName;
delete spec.id;
delete spec.status;
delete spec.failedExpectations;
};
JSR.jasmineDone = function () {
this._buildReport();
};
JSR.getJSReport = function () {
if (jasmine.jsReport) {
return jasmine.jsReport;
}
};
JSR.getJSReportAsString = function () {
if (jasmine.jsReport) {
return JSON.stringify(jasmine.jsReport);
}
};
// Private methods
// ---------------
JSR._haveSpec = function (spec) {
return this.specs[spec.id] != null;
};
JSR._cacheSpec = function (spec) {
var existing = this.specs[spec.id];
if (existing == null) {
existing = this.specs[spec.id] = _clone(spec);
} else {
_extend(existing, spec);
}
return existing;
};
JSR._haveSuite = function (suite) {
return this.suites[suite.id] != null;
};
JSR._cacheSuite = function (suite) {
var existing = this.suites[suite.id];
if (existing == null) {
existing = this.suites[suite.id] = _clone(suite);
} else {
_extend(existing, suite);
}
return existing;
};
JSR._buildReport = function () {
var overallDuration = 0;
var overallPassed = true;
var overallSuites = [];
for (var i = 0, j = this.rootSuites.length; i < j; i++) {
var suite = this.suites[this.rootSuites[i]];
overallDuration += suite.duration;
overallPassed = overallPassed && suite.passed;
overallSuites.push(suite);
}
jasmine.jsReport = {
passed: overallPassed,
durationSec: overallDuration / 1000,
suites: overallSuites
};
};
})(jasmine);

629
test/lib/mock-ajax.js Normal file
View file

@ -0,0 +1,629 @@
/*
Jasmine-Ajax - v3.1.0: a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
http://github.com/jasmine/jasmine-ajax
Jasmine Home page: http://jasmine.github.io/
Copyright (c) 2008-2015 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.eventBus = jRequire.AjaxEventBus();
$ajax.fakeRequest = jRequire.AjaxFakeRequest($ajax.eventBus);
$ajax.MockAjax = jRequire.MockAjax($ajax);
return $ajax.MockAjax;
};
getJasmineRequireObj().AjaxEventBus = function() {
function EventBus() {
this.eventList = {};
}
function ensureEvent(eventList, name) {
eventList[name] = eventList[name] || [];
return eventList[name];
}
function findIndex(list, thing) {
if (list.indexOf) {
return list.indexOf(thing);
}
for(var i = 0; i < list.length; i++) {
if (thing === list[i]) {
return i;
}
}
return -1;
}
EventBus.prototype.addEventListener = function(event, callback) {
ensureEvent(this.eventList, event).push(callback);
};
EventBus.prototype.removeEventListener = function(event, callback) {
var index = findIndex(this.eventList[event], callback);
if (index >= 0) {
this.eventList[event].splice(index, 1);
}
};
EventBus.prototype.trigger = function(event) {
var eventListeners = this.eventList[event];
if(eventListeners){
for(var i = 0; i < eventListeners.length; i++){
eventListeners[i]();
}
}
};
return function() {
return new EventBus();
};
};
getJasmineRequireObj().AjaxFakeRequest = function(eventBusFactory) {
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) {
xhr.eventBus.addEventListener('loadstart', wrapProgressEvent(xhr, 'onloadstart'));
xhr.eventBus.addEventListener('load', wrapProgressEvent(xhr, 'onload'));
xhr.eventBus.addEventListener('loadend', wrapProgressEvent(xhr, 'onloadend'));
xhr.eventBus.addEventListener('progress', wrapProgressEvent(xhr, 'onprogress'));
xhr.eventBus.addEventListener('error', wrapProgressEvent(xhr, 'onerror'));
xhr.eventBus.addEventListener('abort', wrapProgressEvent(xhr, 'onabort'));
xhr.eventBus.addEventListener('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.eventBus = eventBusFactory();
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.eventBus.trigger('progress');
this.eventBus.trigger('abort');
this.eventBus.trigger('loadend');
},
readyState: 0,
onloadstart: null,
onprogress: null,
onabort: null,
onerror: null,
onload: null,
ontimeout: null,
onloadend: null,
onreadystatechange: function(isTimeout) {
},
addEventListener: function() {
this.eventBus.addEventListener.apply(this.eventBus, arguments);
},
removeEventListener: function(event, callback) {
this.eventBus.removeEventListener.apply(this.eventBus, arguments);
},
status: null,
send: function(data) {
this.params = data;
this.readyState = 2;
this.eventBus.trigger('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') + '\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.eventBus.trigger('progress');
this.eventBus.trigger('load');
this.eventBus.trigger('loadend');
},
responseTimeout: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
this.eventBus.trigger('progress');
this.eventBus.trigger('timeout');
this.eventBus.trigger('loadend');
},
responseError: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
this.onreadystatechange();
this.eventBus.trigger('progress');
this.eventBus.trigger('error');
this.eventBus.trigger('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() {
if (global.XMLHttpRequest === mockAjaxFunction) {
throw "MockAjax is already installed.";
}
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.responseHeaders = options.responseHeaders;
};
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);
}
}());

17
test/spec/fakeBlob.js Normal file
View file

@ -0,0 +1,17 @@
/*
* A fake blob used in tests since not every browser supports Blob yet.
*
* @param {Array} blob
*/
function FakeBlob(blob) {
this._blob = blob
this.size = blob.length
}
FakeBlob.prototype.slice = function(start, end) {
return new FakeBlob(this._blob.slice(start, end))
}
FakeBlob.prototype.stringify = function() {
return this._blob.join("")
}

274
test/spec/upload.js Normal file
View file

@ -0,0 +1,274 @@
if (typeof require == "function") {
require("../lib/mock-ajax.js")
}
describe("tus", function() {
describe("#Upload", function() {
beforeEach(function() {
jasmine.Ajax.install()
localStorage.clear()
})
afterEach(function() {
jasmine.Ajax.uninstall()
})
it("should throw if no error handler is available", function() {
var upload = new tus.Upload(null)
expect(upload.start).toThrow()
})
it("should upload a file", function(done) {
var file = new FakeBlob("hello world".split(""))
var options = {
endpoint: "/uploads",
headers: {
Custom: "blargh"
},
metadata: {
foo: "hello",
bar: "world",
nonlatin: "słońce"
},
withCredentials: true,
onProgress: function() {},
fingerprint: function() {}
}
spyOn(options, "fingerprint").and.returnValue("fingerprinted")
spyOn(options, "onProgress")
var upload = new tus.Upload(file, options)
upload.start()
expect(options.fingerprint).toHaveBeenCalledWith(file)
var req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads")
expect(req.method).toBe("POST")
expect(req.withCredentials).toBe(true)
expect(req.requestHeaders.Custom).toBe("blargh")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Length"]).toBe(file.size)
if("btoa" in window) {
expect(req.requestHeaders["Upload-Metadata"]).toBe("foo aGVsbG8=,bar d29ybGQ=,nonlatin c8WCb8WEY2U=")
}
req.respondWith({
status: 201,
responseHeaders: {
Location: "/uploads/blargh"
}
})
expect(upload.url).toBe("/uploads/blargh")
expect(localStorage.getItem("fingerprinted")).toBe("/uploads/blargh")
req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/blargh")
expect(req.method).toBe("PATCH")
expect(req.withCredentials).toBe(true)
expect(req.requestHeaders.Custom).toBe("blargh")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Offset"]).toBe(0)
expect(req.contentType()).toBe("application/offset+octet-stream")
expect(req.params.size).toBe(file.size)
req.respondWith({
status: 204,
responseHeaders: {
"Upload-Offset": file.size
}
})
expect(options.onProgress).toHaveBeenCalledWith(11, 11)
done()
})
it("should resume an upload", function(done) {
localStorage.setItem("fingerprinted", "/uploads/resuming")
var file = new FakeBlob("hello world".split(""))
var options = {
endpoint: "/uploads",
onProgress: function() {},
fingerprint: function() {}
}
spyOn(options, "fingerprint").and.returnValue("fingerprinted")
spyOn(options, "onProgress")
var upload = new tus.Upload(file, options)
upload.start()
expect(options.fingerprint).toHaveBeenCalledWith(file)
var req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/resuming")
expect(req.method).toBe("HEAD")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
req.respondWith({
status: 204,
responseHeaders: {
"Upload-Length": 11,
"Upload-Offset": 3
}
})
expect(upload.url).toBe("/uploads/resuming")
req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/resuming")
expect(req.method).toBe("PATCH")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Offset"]).toBe(3)
expect(req.contentType()).toBe("application/offset+octet-stream")
expect(req.params.size).toBe(file.size - 3)
req.respondWith({
status: 204,
responseHeaders: {
"Upload-Offset": file.size
}
})
expect(options.onProgress).toHaveBeenCalledWith(11, 11)
done()
})
it("should create an upload if resuming fails", function() {
localStorage.setItem("fingerprinted", "/uploads/resuming")
var file = new FakeBlob("hello world".split(""))
var options = {
endpoint: "/uploads",
fingerprint: function() {}
}
spyOn(options, "fingerprint").and.returnValue("fingerprinted")
var upload = new tus.Upload(file, options)
upload.start()
expect(options.fingerprint).toHaveBeenCalledWith(file)
var req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/resuming")
expect(req.method).toBe("HEAD")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
req.respondWith({
status: 404
})
expect(upload.url).toBe(null)
req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads")
expect(req.method).toBe("POST")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Length"]).toBe(11)
})
it("should upload a file in chunks", function(done) {
var file = new FakeBlob("hello world".split(""))
var options = {
endpoint: "/uploads",
chunkSize: 7,
onProgress: function() {},
onChunkComplete: function() {},
fingerprint: function() {}
}
spyOn(options, "fingerprint").and.returnValue("fingerprinted")
spyOn(options, "onProgress")
spyOn(options, "onChunkComplete")
var upload = new tus.Upload(file, options)
upload.start()
expect(options.fingerprint).toHaveBeenCalledWith(file)
var req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads")
expect(req.method).toBe("POST")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Length"]).toBe(file.size)
req.respondWith({
status: 201,
responseHeaders: {
Location: "/uploads/blargh"
}
})
expect(upload.url).toBe("/uploads/blargh")
expect(localStorage.getItem("fingerprinted")).toBe("/uploads/blargh")
req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/blargh")
expect(req.method).toBe("PATCH")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Offset"]).toBe(0)
expect(req.contentType()).toBe("application/offset+octet-stream")
expect(req.params.size).toBe(7)
req.respondWith({
status: 204,
responseHeaders: {
"Upload-Offset": 7
}
})
req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads/blargh")
expect(req.method).toBe("PATCH")
expect(req.requestHeaders["Tus-Resumable"]).toBe("1.0.0")
expect(req.requestHeaders["Upload-Offset"]).toBe(7)
expect(req.contentType()).toBe("application/offset+octet-stream")
expect(req.params.size).toBe(4)
req.respondWith({
status: 204,
responseHeaders: {
"Upload-Offset": file.size
}
})
expect(options.onProgress).toHaveBeenCalledWith(11, 11)
expect(options.onChunkComplete).toHaveBeenCalledWith(7, 7, 11)
expect(options.onChunkComplete).toHaveBeenCalledWith(4, 11, 11)
done()
})
it("should add the original request to errors", function() {
var file = new FakeBlob("hello world".split(""))
var err
var options = {
endpoint: "/uploads",
onError: function(e) {
err = e
},
}
var upload = new tus.Upload(file, options)
upload.start()
var req = jasmine.Ajax.requests.mostRecent()
expect(req.url).toBe("/uploads")
expect(req.method).toBe("POST")
req.respondWith({
status: 500,
responseHeaders: {
Custom: "blargh"
}
})
expect(upload.url).toBe(null)
expect(err.message).toBe("tus: unexpected response while creating upload")
expect(err.originalRequest).toBe(req)
expect(err.originalRequest.getResponseHeader("Custom")).toBe("blargh")
})
})
})