This commit is contained in:
David Walsh 2016-03-02 16:34:31 -06:00
Родитель 792362fffb
Коммит b01ca6c558
4 изменённых файлов: 126 добавлений и 53 удалений

Просмотреть файл

@ -6,53 +6,43 @@ module.exports = function(config) {
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['sw-mocha', 'sinon', 'chai'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'tests/service-worker/*.js', included: false },
{ pattern: 'wp-sw-cache/lib/*.js', included: false }
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'NightlySW'],
@ -67,7 +57,6 @@ module.exports = function(config) {
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true

Просмотреть файл

@ -6,6 +6,11 @@ localforage = {
return Promise.resolve(storage[key]);
},
setItem: function(key, value) {
storage[key] = value;
return Promise.resolve();
},
removeItem: function(key) {
delete storage[key];
return Promise.resolve();
},
clear: function() {

Просмотреть файл

@ -1,36 +1,125 @@
describe('tests', function() {
'use strict';
var cacheName = 'testCache';
var storageKey = 'testCache';
var fakeEvent;
beforeEach(function(done) {
// Needed to prevent SW from bombing on what needs to be replaced
self.$urls = {
'http://localhost/wp-content/themes/my-theme/script.js': '32942374293',
'http://localhost/wp-content/themes/my-theme/style.css': '997898326'
'http://localhost:9876/socket.io/socket.io.js': '328947234',
'http://localhost:9876/karma.js': '32897324923'
};
self.$debug = 1;
beforeEach(function() {
importScripts('/base/wp-sw-cache/lib/service-worker.js');
// Override our utility with a different storage object so we can manipulate
wpSwCache.storage = localforage.createInstance({ name: storageKey });
wpSwCache.cacheName = storageKey;
// Clean up cache and storage before each test
wpSwCache.storage.clear().then(function() {
self.caches.delete(wpSwCache.cacheName).then(function(){
done();
});
});
});
it('This is a stub test', function() {
assert.strictEqual(true, true);
it('URLs which should be added to cache actually end up in cache and storage', function(done) {
this.timeout(10000);
// Simulates a basic install -- check cache and localforage
wpSwCache.update().then(function() {
return self.caches.open(wpSwCache.cacheName).then(function(cache) {
return cache.keys().then(function(keys) {
assert.isTrue(keys.length == 2);
var cacheMatches = 0;
var storageMatches = 0;
return Promise.all(Object.keys(wpSwCache.urls).map(function(key) {
return cache.match(key).then(function(result) {
var isGood = (result && result.url === key);
assert.isTrue(isGood);
if(isGood) {
cacheMatches++;
}
}).then(function() {
return wpSwCache.storage.getItem(key).then(function(result) {
var isGood = (result && result === wpSwCache.urls[key]);
assert.isTrue(isGood);
if(isGood) {
storageMatches++;
}
});
});
})).then(function() {
assert.strictEqual(cacheMatches, keys.length);
done();
});
});
});
});
});
it('URLs which should be added to cache actually end up in cache and storage', function() {
// Simulates a basic install
assert.strictEqual(true, true);
});
it('A URL removed from the `urls` property removes unwanted URLs from cache and storage', function() {
it('A URL removed from the `urls` property removes unwanted URLs from cache and storage', function(done) {
// This is key to removing stale files from cache after an admin no longer wants a file cached
// Simulates a user caching files, going to admin to remove a file, and seeing that file removed from cache+storage
assert.strictEqual(true, true);
var removedUrl;
wpSwCache.update().then(function() {
removedUrl = Object.keys(wpSwCache.urls)[0];
delete wpSwCache.urls[removedUrl];
// The second "update" call simulates teh SW being re-installed/updated
wpSwCache.update().then(function() {
return wpSwCache.removeOldUrls();
}).then(function() {
// Ensure the URL is no longer in cache
return self.caches.open(wpSwCache.cacheName).then(function(cache) {
return cache.match(removedUrl).then(function(result) {
assert.strictEqual(result, undefined);
}).then(function() {
return wpSwCache.storage.getItem(removedUrl).then(function(hash) {
assert.strictEqual(hash, undefined);
done();
});
});
});
});
});
});
it('A URL manually removed from cache after it\'s been cached is re-downloaded and cached', function() {
// https://github.com/darkwing/wp-sw-cache/issues/43
});
it('Debug option works properly', function() {
// We don't want to muddle up the user's console if they option isn't on
wpSwCache.debug = false;
console.log = console.warn = sinon.spy();
wpSwCache.log('Hello');
assert.equal(console.log.callCount, 0);
wpSwCache.debug = true;
wpSwCache.log('Hello2');
assert.equal(console.log.callCount, 1);
});
it('`shouldBeHandled` works properly', function() {
assert.strictEqual(true, true);
// We only want to cache vanilla URLs -- no credentials, query string, etc.
var firstUrl = Object.keys(wpSwCache.urls)[0];
var goodRequest = new Request(firstUrl);
var badRequest = new Request('https://nothing');
var badRequest2 = new Request(firstUrl, {
method: 'POST'
});
assert.isTrue(wpSwCache.shouldBeHandled(goodRequest));
assert.isFalse(wpSwCache.shouldBeHandled(badRequest));
assert.isFalse(wpSwCache.shouldBeHandled(badRequest2));
});
});

Просмотреть файл

@ -9,6 +9,8 @@
// A { url: hash } object which will be used to populate cache
// A changed url object will ensure the SW is downloaded when URLs change
urls: $urls,
// Allowed to use console functions?
debug: $debug,
// Instance of localForage to save urls and hashes to see if anything has changed
storage: localforage.createInstance({ name: storageKey }),
// Name of the cache the plugin will use
@ -56,21 +58,13 @@
return self.caches.open(this.cacheName).then(cache => {
return cache.add(url).then(() => {
// ... and once it's successful add its hash to storage
return this.storage.setItem(url, hash).catch(e => {
this.warn('[update] error: ', e)
return this.storage.setItem(url, hash);
});
})
.catch(e => {
this.warn('[update] error: ', e)
});
})
.catch(e => {
this.warn('[update] error: ', e)
});
})
.catch(e => {
this.warn('[update] error: ', e)
this.warn('[update] error: ', e);
});
}));
},
@ -81,25 +75,21 @@
return cache.keys().then(keys => {
return Promise.all(keys.map(key => {
if(!(key.url in this.urls)) {
this.log('[removeOldUrls] Removing URL no longer desired: ', key.url);
return cache.delete(key).then(() => {
return this.storage.removeItem(key.url).catch(e => {
this.warn('[removeOldUrls] error: ', e)
});
})
.catch(e => {
this.warn('[removeOldUrls] error: ', e)
});
return this.removeOldUrl(cache, key);
}
return Promise.resolve();
}));
})
.catch(e => {
this.warn('[removeOldUrls] error: ', e)
})
})
.catch(e => {
this.warn('[removeOldUrls] error: ', e)
this.warn('[removeOldUrls] error: ', e);
});
},
// Removes one individual URL from cache and storage
removeOldUrl: function(cache, request) {
this.log('[removeOldUrl] Removing URL no longer desired: ', request.url);
return cache.delete(request).then(() => {
return this.storage.removeItem(request.url);
});
},
// Install step that kicks off adding/updating URLs in cache and storage
@ -142,7 +132,7 @@
// Add debugging functions
['log', 'warn'].forEach(function(level) {
wpSwCache[level] = function() {
if($debug) {
if(this.debug) {
console[level].apply(console, arguments);
}
};