Skip to content

Commit

Permalink
Update tests to run in a SW env
Browse files Browse the repository at this point in the history
  • Loading branch information
philipwalton committed Mar 28, 2019
1 parent 5b8e1c7 commit 47bf2c0
Show file tree
Hide file tree
Showing 13 changed files with 194 additions and 265 deletions.
12 changes: 6 additions & 6 deletions infra/testing/helpers/extendable-event-utils.mjs
Expand Up @@ -20,29 +20,29 @@ export const eventDoneWaiting = async (event) => {
}
};

export const watchEvent = (event) => {
export const spyOnEvent = (event) => {
const promises = [];
extendLifetimePromises.set(event, promises);

event.waitUntil = (promise) => {
event.waitUntil = sinon.stub().callsFake((promise) => {
promises.push(promise);
};
});

if (event instanceof FetchEvent) {
event.respondWith = (responseOrPromise) => {
event.respondWith = sinon.stub().callsFake((responseOrPromise) => {
eventResponses.set(event, responseOrPromise);
promises.push(Promise.resolve(responseOrPromise));

// TODO(philipwalton): we cannot currently call the native
// `respondWith()` due to this bug in Firefix:
// https://bugzilla.mozilla.org/show_bug.cgi?id=1538756
// FetchEvent.prototype.respondWith.call(event, responseOrPromise);
};
});
}
};

export const dispatchAndWaitUntilDone = async (event) => {
watchEvent(event);
spyOnEvent(event);
self.dispatchEvent(event);
await eventDoneWaiting(event);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/workbox-routing/Router.mjs
Expand Up @@ -105,7 +105,7 @@ class Router {
event.waitUntil(requestPromises);

// If a MessageChannel was used, reply to the message on success.
if (event.ports) {
if (event.ports && event.ports[0]) {
await requestPromises;
event.ports[0].postMessage(true);
}
Expand Down
16 changes: 16 additions & 0 deletions test/workbox-routing/integration/test-sw.js
@@ -0,0 +1,16 @@
/*
Copyright 2019 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/

const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests');


describe(`[workbox-routing]`, function() {
it(`passes all SW unit tests`, async function() {
await runUnitTests('/test/workbox-routing/sw/');
});
});
12 changes: 6 additions & 6 deletions test/workbox-routing/sw/test-NavigationRoute.mjs
Expand Up @@ -6,10 +6,8 @@
https://opensource.org/licenses/MIT.
*/

import {expect} from 'chai';
import expectError from '../../../infra/testing/expectError.js';
import {devOnly} from '../../../infra/testing/env-it';
import {NavigationRoute} from '../../../packages/workbox-routing/NavigationRoute.mjs';
import {NavigationRoute} from 'workbox-routing/NavigationRoute.mjs';


const handler = {
handle: () => {},
Expand All @@ -18,8 +16,10 @@ const functionHandler = () => {};

const invalidHandlerObject = {};

describe(`[workbox-routing] NavigationRoute`, function() {
devOnly.it(`should throw when called without a valid handler parameter in dev`, async function() {
describe(`NavigationRoute`, function() {
it(`should throw when called without a valid handler parameter in dev`, async function() {
if (process.env.NODE_ENV === 'production') this.skip();

await expectError(
() => new NavigationRoute(),
'incorrect-type',
Expand Down
14 changes: 6 additions & 8 deletions test/workbox-routing/sw/test-RegExpRoute.mjs
Expand Up @@ -6,14 +6,10 @@
https://opensource.org/licenses/MIT.
*/

import sinon from 'sinon';
import {expect} from 'chai';
import {RegExpRoute} from 'workbox-routing/RegExpRoute.mjs';

import {RegExpRoute} from '../../../packages/workbox-routing/RegExpRoute.mjs';
import expectError from '../../../infra/testing/expectError.js';
import {devOnly} from '../../../infra/testing/env-it.js';

describe(`[workbox-routing] RegExpRoute`, function() {
describe(`RegExpRoute`, function() {
const SAME_ORIGIN_URL = new URL('https://example.com');
const CROSS_ORIGIN_URL = new URL('https://cross-origin-example.com');
const PATH = '/test/path';
Expand All @@ -22,14 +18,16 @@ describe(`[workbox-routing] RegExpRoute`, function() {
const sandbox = sinon.createSandbox();
beforeEach(function() {
sandbox.restore();
sandbox.stub(global, 'location').value(SAME_ORIGIN_URL);
sandbox.stub(self, 'location').value(SAME_ORIGIN_URL);
});
after(function() {
sandbox.restore();
});

for (const badRegExp of [undefined, null, 123, '123', {}]) {
devOnly.it(`should throw when called with a regExp parameter of ${JSON.stringify(badRegExp)} in dev`, async function() {
it(`should throw when called with a regExp parameter of ${JSON.stringify(badRegExp)} in dev`, async function() {
if (process.env.NODE_ENV === 'production') this.skip();

await expectError(
() => new RegExpRoute(),
'incorrect-class',
Expand Down
7 changes: 3 additions & 4 deletions test/workbox-routing/sw/test-Route.mjs
Expand Up @@ -6,9 +6,8 @@
https://opensource.org/licenses/MIT.
*/

import {expect} from 'chai';
import expectError from '../../../infra/testing/expectError.js';
import {Route} from '../../../packages/workbox-routing/Route.mjs';
import {Route} from 'workbox-routing/Route.mjs';


const match = () => {};
const handler = {
Expand All @@ -20,7 +19,7 @@ const method = 'POST';
const invalidHandlerObject = {};
const invalidMethod = 'INVALID';

describe(`workbox-routing: Route`, function() {
describe(`Route`, function() {
it(`should throw when called without any parameters in dev`, async function() {
if (process.env.NODE_ENV === 'production') return this.skip();

Expand Down
86 changes: 40 additions & 46 deletions test/workbox-routing/sw/test-Router.mjs
Expand Up @@ -6,33 +6,31 @@
https://opensource.org/licenses/MIT.
*/

import sinon from 'sinon';
import {expect} from 'chai';

import {Route} from '../../../packages/workbox-routing/Route.mjs';
import {Router} from '../../../packages/workbox-routing/Router.mjs';
import expectError from '../../../infra/testing/expectError';
import {eventsDoneWaiting, resetEventListeners} from '../../../infra/testing/sw-env-mocks/event-listeners';
import {Route} from 'workbox-routing/Route.mjs';
import {Router} from 'workbox-routing/Router.mjs';
import {dispatchAndWaitUntilDone} from '../../../infra/testing/helpers/extendable-event-utils.mjs';
import generateTestVariants from '../../../infra/testing/generate-variant-tests';

describe(`[workbox-routing] Router`, function() {

describe(`Router`, function() {
const sandbox = sinon.createSandbox();
const MATCH = () => {};
const HANDLER = {handle: () => {}};
const METHOD = 'POST';
const EXPECTED_RESPONSE_BODY = 'test body';

beforeEach(async function() {
// Run this in the `beforeEach` hook as well as the afterEach hook due to
// a mocha bug where `afterEach` hooks aren't run for skipped tests.
// https://github.com/mochajs/mocha/issues/2546
sandbox.restore();
resetEventListeners();

// Spy on all added event listeners so they can be removed.
sandbox.spy(self, 'addEventListener');
});

after(function() {
afterEach(function() {
for (const args of self.addEventListener.args) {
self.removeEventListener(...args);
}
sandbox.restore();
resetEventListeners();
});

describe(`constructor`, function() {
Expand Down Expand Up @@ -148,37 +146,39 @@ describe(`[workbox-routing] Router`, function() {
router.registerRoute(route);
router.addFetchListener();

const request = new Request(location);
const event = new FetchEvent('fetch', {request});
sandbox.spy(router, 'handleRequest');
sandbox.spy(event, 'respondWith');

self.dispatchEvent(event);
const request = new Request(location);
const fetchEvent = new FetchEvent('fetch', {request});

await dispatchAndWaitUntilDone(fetchEvent);

expect(router.handleRequest.callCount).to.equal(1);
expect(router.handleRequest.args[0][0].request).to.equal(request);
expect(router.handleRequest.args[0][0].event).to.equal(event);
expect(event.respondWith.callCount).to.equal(1);
expect(router.handleRequest.args[0][0].event).to.equal(fetchEvent);
expect(fetchEvent.respondWith.callCount).to.equal(1);

const response = await event.respondWith.args[0][0];
const response = fetchEvent.respondWith.args[0][0];
expect(await response.text()).to.equal(EXPECTED_RESPONSE_BODY);
});

it(`should not call respondWith when no routes match`, function() {
it(`should not call respondWith when no routes match`, async function() {
const router = new Router();
const route = new Route(
() => false,
() => new Response(EXPECTED_RESPONSE_BODY));
router.registerRoute(route);
router.addFetchListener();

const request = new Request(location.href + '?foo');
const event = new FetchEvent('fetch', {request});
sandbox.spy(router, 'handleRequest');
sandbox.spy(event, 'respondWith');

self.dispatchEvent(event);
const request = new Request(location.href + '?foo');
const fetchEvent = new FetchEvent('fetch', {request});

await dispatchAndWaitUntilDone(fetchEvent);

expect(router.handleRequest.callCount).to.equal(1);
expect(event.respondWith.callCount).to.equal(0);
expect(fetchEvent.respondWith.callCount).to.equal(0);
});
});

Expand All @@ -191,29 +191,27 @@ describe(`[workbox-routing] Router`, function() {
router.registerRoute(route);
router.addCacheListener();

const event = new ExtendableMessageEvent('message', {
sandbox.spy(router, 'handleRequest');

const messageEvent = new ExtendableMessageEvent('message', {
data: {
type: 'CACHE_URLS',
payload: {
urlsToCache: ['/one', '/two', '/three'],
},
},
});
event.ports = [{postMessage: sinon.spy()}];
sinon.spy(event, 'waitUntil');

sandbox.spy(router, 'handleRequest');
self.dispatchEvent(event);
sandbox.stub(messageEvent, 'ports').value([{postMessage: sinon.spy()}]);

await eventsDoneWaiting();
await dispatchAndWaitUntilDone(messageEvent);

expect(router.handleRequest.callCount).to.equal(3);
expect(router.handleRequest.args[0][0].request.url).to.equal(`${location.origin}/one`);
expect(router.handleRequest.args[1][0].request.url).to.equal(`${location.origin}/two`);
expect(router.handleRequest.args[2][0].request.url).to.equal(`${location.origin}/three`);
expect(event.waitUntil.callCount).to.equal(1);
expect(event.waitUntil.args[0][0]).to.be.instanceOf(Promise);
expect(event.ports[0].postMessage.callCount).to.equal(1);
expect(messageEvent.waitUntil.callCount).to.equal(1);
expect(messageEvent.waitUntil.args[0][0]).to.be.instanceOf(Promise);
expect(messageEvent.ports[0].postMessage.callCount).to.equal(1);
});

it(`should accept URL strings or request URL+requestInit tuples`, async function() {
Expand All @@ -224,7 +222,9 @@ describe(`[workbox-routing] Router`, function() {
router.registerRoute(route);
router.addCacheListener();

const event = new ExtendableMessageEvent('message', {
sandbox.spy(router, 'handleRequest');

await dispatchAndWaitUntilDone(new ExtendableMessageEvent('message', {
data: {
type: 'CACHE_URLS',
payload: {
Expand All @@ -235,11 +235,7 @@ describe(`[workbox-routing] Router`, function() {
],
},
},
});
sandbox.spy(router, 'handleRequest');
self.dispatchEvent(event);

await eventsDoneWaiting();
}));

expect(router.handleRequest.callCount).to.equal(3);
expect(router.handleRequest.args[0][0].request.url).to.equal(`${location.origin}/one`);
Expand All @@ -256,11 +252,9 @@ describe(`[workbox-routing] Router`, function() {
router.registerRoute(route);
router.addCacheListener();

const event = new ExtendableMessageEvent('message');
sandbox.spy(router, 'handleRequest');

self.dispatchEvent(event);
await eventsDoneWaiting();
await dispatchAndWaitUntilDone(new ExtendableMessageEvent('message'));

expect(router.handleRequest.callCount).to.equal(0);
});
Expand Down
51 changes: 0 additions & 51 deletions test/workbox-routing/sw/test-index.mjs

This file was deleted.

0 comments on commit 47bf2c0

Please sign in to comment.