From 63ea2ca52e7278411a71520f48bd9cf700694edd Mon Sep 17 00:00:00 2001 From: Jeffrey Posnick Date: Thu, 26 Aug 2021 17:57:20 -0400 Subject: [PATCH] Enable prettier (#2929) * Deps and config * Prettier output * Update hardcoded file sizes * More file size updates --- .github/ISSUE_TEMPLATE.md | 8 +- .github/PULL_REQUEST_TEMPLATE.md | 5 +- .github/workflows/pull-request.yml | 80 +- .husky/pre-commit | 4 + .husky/pre-push | 4 + .prettierignore | 13 + CONTRIBUTING.md | 7 +- README.md | 6 +- .../workbox-background-sync-demo/index.html | 81 +- .../workbox-background-sync-demo/package.json | 28 +- demos/src/workbox-background-sync-demo/sw.js | 15 +- .../updateServer.js | 4 +- .../workbox-broadcast-update-demo/index.html | 60 +- .../package.json | 28 +- demos/src/workbox-broadcast-update-demo/sw.js | 7 +- .../updateServer.js | 4 +- .../src/workbox-cacheable-response/index.html | 86 +- .../workbox-cacheable-response/package.json | 2 +- .../src/workbox-cacheable-response/server.js | 29 +- demos/src/workbox-cacheable-response/sw.js | 22 +- demos/src/workbox-core/index.html | 93 +- demos/src/workbox-core/package.json | 28 +- demos/src/workbox-core/sw.js | 4 +- demos/src/workbox-core/updateServer.js | 4 +- demos/src/workbox-expiration/index.html | 100 +- demos/src/workbox-expiration/package.json | 28 +- demos/src/workbox-expiration/sw.js | 18 +- demos/src/workbox-expiration/updateServer.js | 4 +- demos/src/workbox-google-analytics/index.html | 92 +- .../src/workbox-google-analytics/package.json | 28 +- demos/src/workbox-google-analytics/sw.js | 5 +- .../workbox-google-analytics/updateServer.js | 4 +- .../src/workbox-navigation-preload/index.html | 57 +- .../workbox-navigation-preload/package.json | 28 +- demos/src/workbox-navigation-preload/sw.js | 4 +- .../updateServer.js | 4 +- demos/src/workbox-precaching/index.html | 98 +- demos/src/workbox-precaching/package.json | 28 +- demos/src/workbox-precaching/sw-1.js | 4 +- demos/src/workbox-precaching/sw-2.js | 4 +- demos/src/workbox-precaching/updateServer.js | 4 +- demos/src/workbox-range-requests/index.html | 84 +- demos/src/workbox-range-requests/package.json | 28 +- demos/src/workbox-range-requests/sw.js | 16 +- .../workbox-range-requests/updateServer.js | 4 +- demos/src/workbox-routing/index.html | 77 +- demos/src/workbox-routing/package.json | 28 +- demos/src/workbox-routing/sw.js | 4 +- demos/src/workbox-routing/updateServer.js | 4 +- demos/src/workbox-strategies/index.html | 131 +- demos/src/workbox-strategies/sw.js | 19 +- demos/src/workbox-strategies/updateServer.js | 4 +- demos/src/workbox-streams/index.html | 56 +- demos/src/workbox-streams/package.json | 2 +- demos/src/workbox-streams/server.js | 10 +- demos/src/workbox-streams/sw.js | 34 +- demos/src/workbox-sw/index.html | 77 +- demos/src/workbox-sw/package.json | 28 +- demos/src/workbox-sw/sw.js | 26 +- demos/src/workbox-sw/updateServer.js | 4 +- demos/src/workbox-window/index.html | 63 +- demos/src/workbox-window/package.json | 28 +- demos/src/workbox-window/sw.js | 4 +- demos/src/workbox-window/updateServer.js | 4 +- gulp-tasks/build-node-packages.js | 49 +- gulp-tasks/build-packages.js | 22 +- gulp-tasks/build-sw-packages.js | 44 +- gulp-tasks/build-window-packages.js | 34 +- gulp-tasks/build.js | 28 +- gulp-tasks/docs.js | 21 +- gulp-tasks/lint.js | 32 +- gulp-tasks/publish-github.js | 10 +- gulp-tasks/publish-glitch.js | 12 +- gulp-tasks/publish-lerna.js | 7 +- gulp-tasks/publish.js | 12 +- gulp-tasks/test-integration.js | 14 +- gulp-tasks/test-node.js | 50 +- gulp-tasks/test-server.js | 13 +- gulp-tasks/transpile-typescript.js | 5 +- gulp-tasks/utils/analyse-properties.js | 71 +- gulp-tasks/utils/cdn-helper.js | 7 +- gulp-tasks/utils/get-packages.js | 14 +- gulp-tasks/utils/github-helper.js | 6 +- .../utils/node-projects-babel.config.json | 4 +- .../utils/output-filename-to-package-map.js | 2 - gulp-tasks/utils/package-runner.js | 24 +- gulp-tasks/utils/publish-helpers.js | 38 +- gulp-tasks/utils/rollup-helper.js | 35 +- gulp-tasks/utils/version-module.js | 9 +- gulp-tasks/utils/versioned-cdn-url.js | 4 +- gulpfile.js | 6 +- infra/pr-bot/aggregate-size-plugin.js | 3 +- .../reference-docs/jsdoc/lang/en.yaml | 78 +- .../reference-docs/jsdoc/lib/publishjob.js | 18 +- .../templates/reference-docs/jsdoc/publish.js | 51 +- .../reference-docs/jsdoc/static/jsdoc.css | 7 +- infra/testing/activate-and-control.js | 101 +- infra/testing/activate-sw-safari.js | 84 +- infra/testing/auto-stub-logger.mjs | 4 +- infra/testing/clean-sw.js | 14 +- infra/testing/comlink/node-interface.js | 26 +- infra/testing/comlink/sw-interface.js | 12 +- infra/testing/comlink/window-interface.js | 4 +- infra/testing/confirm-directory-contains.js | 5 +- infra/testing/env-it.js | 12 +- infra/testing/generate-variant-tests.js | 12 +- infra/testing/helpers/compareResponses.mjs | 5 +- .../helpers/extendable-event-utils.mjs | 3 +- .../helpers/generateOpaqueResponse.mjs | 1 - .../helpers/generateUniqueResponse.mjs | 1 - infra/testing/server/index.js | 4 +- infra/testing/server/routes/build-file.js | 6 +- infra/testing/server/routes/sw-bundle.js | 3 +- .../testing/server/routes/templates-update.js | 1 - infra/testing/server/routes/templates.js | 1 - infra/testing/server/routes/test-sw.js | 4 +- infra/testing/server/routes/test-window.js | 3 +- infra/testing/server/static/integration.html | 2 +- .../validator/service-worker-runtime.js | 63 +- infra/testing/webdriver/IframeManager.js | 42 +- .../testing/webdriver/executeAsyncAndCatch.js | 1 - infra/testing/webdriver/runUnitTests.js | 11 +- infra/testing/webdriver/unregisterAllSWs.js | 1 - infra/testing/webdriver/windowLoaded.js | 5 +- infra/type-overrides.d.ts | 25 +- infra/utils/log-helper.js | 2 +- javascript.eslintrc.js | 207 ++- lerna.json | 4 +- package-lock.json | 86 +- package.json | 13 +- test/all/node/test-exports.js | 54 +- test/all/node/test-jsdocs.js | 33 +- test/all/node/test-package.js | 96 +- test/all/node/test-prod-builds.js | 39 +- test/all/node/test-yarn-installation.js | 6 +- .../integration/test-all.js | 29 +- .../static/basic-example/index.html | 5 +- .../static/basic-example/sw.js | 13 +- .../sw/lib/test-QueueDb.mjs | 1 - .../sw/lib/test-QueueStore.mjs | 40 +- .../sw/lib/test-StorableRequest.mjs | 78 +- .../sw/test-BackgroundSyncPlugin.mjs | 10 +- .../workbox-background-sync/sw/test-Queue.mjs | 264 +-- .../integration/test-all.js | 68 +- .../static/index.html | 5 +- test/workbox-broadcast-update/static/sw.js | 42 +- .../sw/test-BroadcastCacheUpdate.mjs | 54 +- .../sw/test-BroadcastUpdatePlugin.mjs | 15 +- .../sw/test-responsesAreSame.mjs | 45 +- test/workbox-build/node/dependency-check.js | 100 +- test/workbox-build/node/generate-sw.js | 1548 ++++++++++------- test/workbox-build/node/get-manifest.js | 384 ++-- test/workbox-build/node/inject-manifest.js | 375 ++-- .../additional-manifest-entries-transform.js | 26 +- test/workbox-build/node/lib/bundle.js | 101 +- test/workbox-build/node/lib/cdn-utils.js | 20 +- .../node/lib/copy-workbox-libraries.js | 13 +- test/workbox-build/node/lib/escape-regexp.js | 8 +- .../node/lib/get-composite-details.js | 10 +- .../node/lib/get-file-details.js | 36 +- test/workbox-build/node/lib/get-file-hash.js | 9 +- .../node/lib/get-file-manifest-entries.js | 59 +- test/workbox-build/node/lib/get-file-size.js | 15 +- .../node/lib/get-string-details.js | 34 +- .../workbox-build/node/lib/get-string-hash.js | 8 +- .../node/lib/modify-url-prefix-transform.js | 99 +- .../workbox-build/node/lib/module-registry.js | 18 +- ...no-revision-for-urls-matching-transform.js | 111 +- .../node/lib/populate-sw-template.js | 136 +- .../node/lib/replace-and-update-source-map.js | 10 +- .../node/lib/runtime-caching-converter.js | 437 +++-- .../node/lib/transform-manifest.js | 129 +- .../node/lib/validate-options.js | 36 +- .../lib/write-sw-using-default-template.js | 59 +- .../static/example-project-1/index.html | 68 +- .../static/example-project-1/webpackEntry.js | 1 - .../static/sw-injections/sample-import.js | 1 - .../integration/test-all.js | 23 +- .../static/cacheable-response-plugin/sw.js | 26 +- .../sw/test-CacheableResponse.mjs | 157 +- .../sw/test-CacheableResponsePlugin.mjs | 54 +- test/workbox-cli/node/app.js | 84 +- test/workbox-cli/node/dependency-check.js | 62 +- .../node/lib/cleanup-stack-trace.js | 15 +- test/workbox-cli/node/lib/help-text.js | 9 +- test/workbox-cli/node/lib/logger.js | 15 +- .../node/lib/questions/ask-config-location.js | 14 +- .../lib/questions/ask-extensions-to-cache.js | 30 +- .../node/lib/questions/ask-questions.js | 33 +- .../node/lib/questions/ask-root-of-web-app.js | 58 +- .../questions/ask-start_url-query-params.js | 113 +- .../node/lib/questions/ask-sw-dest.js | 18 +- .../node/lib/questions/ask-sw-src.js | 10 +- test/workbox-cli/node/lib/run-wizard.js | 7 +- test/workbox-core/integration/test-all.js | 9 +- .../static/core-in-browser/index.html | 5 +- test/workbox-core/static/logger.html | 189 +- .../sw/_private/test-Deferred.mjs | 15 +- test/workbox-core/sw/_private/test-assert.mjs | 84 +- .../_private/test-cacheMatchIgnoreParams.mjs | 15 +- .../test-executeQuotaErrorCallbacks.mjs | 11 +- .../sw/_private/test-getFriendlyURL.mjs | 15 +- test/workbox-core/sw/_private/test-logger.mjs | 40 +- .../_private/test-resultingClientExists.mjs | 37 +- .../workbox-core/sw/_private/test-timeout.mjs | 9 +- .../sw/_private/test-waitUntil.mjs | 9 +- .../models/messages/test-messageGenerator.mjs | 17 +- test/workbox-core/sw/test-cacheNames.mjs | 184 +- test/workbox-core/sw/test-clientsClaim.mjs | 7 +- test/workbox-core/sw/test-copyResponse.mjs | 34 +- .../sw/test-registerQuotaErrorCallback.mjs | 5 +- test/workbox-core/sw/test-skipWaiting.mjs | 8 +- .../integration/test-all.js | 86 +- .../static/expiration-plugin/sw-deletion.js | 12 +- .../expiration-plugin/sw-max-age-seconds.js | 26 +- .../expiration-plugin/sw-max-entries.js | 26 +- .../static/isURLExpired.html | 60 +- .../sw/test-CacheExpiration.mjs | 116 +- .../sw/test-CacheTimestampsModel.mjs | 37 +- .../sw/test-ExpirationPlugin.mjs | 110 +- .../integration/test-all.js | 43 +- .../static/basic-example/index.html | 28 +- .../static/basic-example/sw.js | 15 +- .../sw/test-initialize.mjs | 391 +++-- .../integration/test-disable.js | 12 +- .../integration/test-enable.js | 26 +- .../integration/test-sw.js | 5 +- .../static/sw-custom-header.js | 2 +- .../static/sw-default-header.js | 2 +- .../static/sw-disable.js | 2 +- .../sw/test-disable.mjs | 15 +- .../sw/test-enable.mjs | 25 +- .../sw/test-isSupported.mjs | 5 +- .../test-cleanup-outdated-caches.js | 36 +- .../integration/test-precache-and-update.js | 83 +- .../workbox-precaching/integration/test-sw.js | 5 +- .../static/addToCacheList.html | 36 +- .../static/cleanup-outdated-caches/sw.js | 18 +- .../static/precache-and-update/index.html | 10 +- .../static/precache-and-update/sw-1.js | 11 +- .../static/precache-and-update/sw-2.js | 8 +- test/workbox-precaching/static/precache.html | 86 +- .../sw/resetDefaultPrecacheController.mjs | 1 - .../sw/test-PrecacheController.mjs | 370 ++-- .../sw/test-PrecacheFallbackPlugin.mjs | 36 +- .../sw/test-PrecacheRoute.mjs | 50 +- .../sw/test-PrecacheStrategy.mjs | 128 +- .../workbox-precaching/sw/test-addPlugins.mjs | 5 +- test/workbox-precaching/sw/test-addRoute.mjs | 9 +- .../sw/test-cleanupOutdatedCaches.mjs | 10 +- .../sw/test-createHandlerBoundToURL.mjs | 50 +- .../sw/test-getCacheKeyForURL.mjs | 14 +- .../sw/test-matchPrecache.mjs | 29 +- test/workbox-precaching/sw/test-precache.mjs | 18 +- .../sw/test-precacheAndRoute.mjs | 11 +- .../sw/utils/test-deleteOutdatedCaches.mjs | 75 +- .../sw/utils/test-printCleanupDetails.mjs | 13 +- .../sw/utils/test-printInstallDetails.mjs | 9 +- .../integration/test-all.js | 36 +- test/workbox-range-requests/static/index.html | 5 +- test/workbox-range-requests/static/sw.js | 23 +- .../sw/test-RangeRequestsPlugin.mjs | 15 +- .../sw/test-createPartialResponse.mjs | 68 +- .../test-calculateEffectiveBoundaries.mjs | 66 +- .../sw/utils/test-parseRangeHeader.mjs | 56 +- .../integration/test-navigation-route.js | 4 +- .../integration/test-routing-basic.js | 48 +- .../integration/test-routing-regex.js | 59 +- test/workbox-routing/integration/test-sw.js | 5 +- .../static/routing-basic/index.html | 3 +- .../static/routing-basic/sw.js | 14 +- .../static/routing-navigation/index.html | 5 +- .../static/routing-navigation/sw.js | 16 +- .../static/routing-regex/index.html | 5 +- .../static/routing-regex/sw.js | 46 +- test/workbox-routing/static/routing.html | 27 +- test/workbox-routing/static/sw.js | 29 +- .../sw/test-NavigationRoute.mjs | 71 +- test/workbox-routing/sw/test-RegExpRoute.mjs | 70 +- test/workbox-routing/sw/test-Route.mjs | 129 +- test/workbox-routing/sw/test-Router.mjs | 605 ++++--- .../workbox-routing/sw/test-registerRoute.mjs | 80 +- .../sw/test-setCatchHandler.mjs | 8 +- .../sw/test-setDefaultHandler.mjs | 8 +- .../sw/utils/test-normalizeHandler.mjs | 63 +- .../integration/test-cacheFirst.js | 46 +- .../integration/test-cacheOnly.js | 18 +- .../integration/test-networkFirst.js | 30 +- .../integration/test-networkOnly.js | 18 +- .../integration/test-staleWhileRevalidate.js | 30 +- .../workbox-strategies/integration/test-sw.js | 5 +- .../static/cache-first/sw.js | 12 +- .../static/cache-only/sw.js | 19 +- .../static/network-first/sw.js | 19 +- .../static/network-only/sw.js | 25 +- .../static/stale-while-revalidate/sw.js | 16 +- .../plugins/test-cacheOkAndOpaquePlugin.mjs | 21 +- .../workbox-strategies/sw/test-CacheFirst.mjs | 49 +- test/workbox-strategies/sw/test-CacheOnly.mjs | 42 +- .../sw/test-NetworkFirst.mjs | 84 +- .../sw/test-NetworkOnly.mjs | 45 +- .../sw/test-StaleWhileRevalidate.mjs | 47 +- test/workbox-strategies/sw/test-Strategy.mjs | 430 +++-- .../sw/test-StrategyHandler.mjs | 486 ++++-- .../sw/test-UsageWithRouter.mjs | 22 +- test/workbox-streams/integration/test-all.js | 38 +- test/workbox-streams/static/sw.js | 25 +- test/workbox-streams/sw/test-isSupported.mjs | 5 +- .../sw/utils/test-createHeaders.mjs | 13 +- test/workbox-sw/integration/test-all.js | 20 +- test/workbox-sw/static/index.html | 12 +- test/workbox-sw/static/integration/index.html | 5 +- .../workbox-sw/static/integration/valid-sw.js | 4 +- test/workbox-sw/static/sw.js | 5 +- .../sw/controllers/test-WorkboxSW.mjs | 100 +- .../node/dependency-check.js | 71 +- .../node/v4/generate-sw.js | 1020 ++++++----- .../node/v4/inject-manifest.js | 939 ++++++---- .../v4/lib/create-webpack-asset-plugin.js | 7 +- .../node/v5/generate-sw.js | 999 +++++++---- .../node/v5/inject-manifest.js | 917 ++++++---- .../v5/lib/create-webpack-asset-plugin.js | 8 +- .../static/example-project-1/index.html | 68 +- test/workbox-window/integration/test-all.js | 30 +- test/workbox-window/static/index.html | 58 +- test/workbox-window/window/test-Workbox.mjs | 187 +- tsconfig.json | 30 +- typescript.eslintrc.js | 13 +- 328 files changed, 11480 insertions(+), 7821 deletions(-) create mode 100755 .husky/pre-commit create mode 100755 .husky/pre-push create mode 100644 .prettierignore diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 2f719254a..0fbf1a97c 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,12 +1,12 @@ Welcome! Please use this template for reporting bugs or requesting features. For questions about using Workbox, the best place to ask is Stack Overflow, tagged with `[workbox]`: https://stackoverflow.com/questions/ask?tags=workbox **Library Affected**: -*workbox-sw, workbox-build, etc.* +_workbox-sw, workbox-build, etc._ **Browser & Platform**: -*E.g. Google Chrome v51.0.1 for Android, or "all browsers".* +_E.g. Google Chrome v51.0.1 for Android, or "all browsers"._ **Issue or Feature Request Description**: -*Your request here.* +_Your request here._ -*When reporting bugs, please include relevant JavaScript Console logs and links to public URLs at which the issue could be reproduced.* +_When reporting bugs, please include relevant JavaScript Console logs and links to public URLs at which the issue could be reproduced._ diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 33e73b8a9..f5f6ab5a4 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,9 +1,10 @@ **Prior to filing a PR, please:** + - [open an issue](https://github.com/GoogleChrome/workbox/issues/new) to discuss your proposed change. - ensure that `gulp build && gulp lint test` passes locally. R: @jeffposnick @tropicadri -Fixes #*issue number* +Fixes #_issue number_ -*Description of what's changed/fixed.* +_Description of what's changed/fixed._ diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 4fe8dd0c2..b201a7bb7 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -7,52 +7,52 @@ jobs: runs-on: windows-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v2 - - uses: actions/cache@v1 - with: - path: ~/.npm - key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-node- + - uses: actions/cache@v1 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- - - uses: actions/setup-node@v1 - with: - node-version: 10.x + - uses: actions/setup-node@v1 + with: + node-version: 10.x - - name: Setup - run: | - npm ci - npx gulp build + - name: Setup + run: | + npm ci + npx gulp build - - run: npx gulp test_node + - run: npx gulp test_node Full_Suite_Mac: runs-on: macos-latest steps: - - uses: actions/checkout@v2 - - - uses: actions/cache@v1 - with: - path: ~/.npm - key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} - restore-keys: | - ${{ runner.os }}-node- - - - uses: actions/cache@v1 - with: - path: ~/.selenium-assistant - key: ${{ runner.os }} - - - uses: actions/setup-node@v1 - with: - node-version: 12.x - - - name: Setup - run: | - sudo safaridriver --enable - npm ci - npx gulp build - - - run: npx gulp test + - uses: actions/checkout@v2 + + - uses: actions/cache@v1 + with: + path: ~/.npm + key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-node- + + - uses: actions/cache@v1 + with: + path: ~/.selenium-assistant + key: ${{ runner.os }} + + - uses: actions/setup-node@v1 + with: + node-version: 12.x + + - name: Setup + run: | + sudo safaridriver --enable + npm ci + npx gulp build + + - run: npx gulp test diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 000000000..5915c217b --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npm run format-staged diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100755 index 000000000..20d0d06e5 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,4 @@ +#!/bin/sh +. "$(dirname "$0")/_/husky.sh" + +npm run lint diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..e1d797e78 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,13 @@ +.nyc_output +.vscode +*.hbs +*.log +build +coverage +docs +generated-release-files +node_modules +packages/** +!packages/*/src/** +temp +test/workbox-webpack-plugin/static/injected-manifest.json diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03924468a..94c8d4cfb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,8 +5,9 @@ We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles. Please fill out either the individual or corporate Contributor License Agreement (CLA). - * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). - * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). + +- If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). +- If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. @@ -42,4 +43,4 @@ To do an automated run of the full test suite for the browser-based code against ``` npm run gulp test_integration -``` \ No newline at end of file +``` diff --git a/README.md b/README.md index d9c097203..a756f30e6 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,9 @@ Workbox is a collection of JavaScript libraries for ## Documentation -* [Overview](https://developers.google.com/web/tools/workbox/) ([site source](https://github.com/google/WebFundamentals/tree/main/src/content/en/tools/workbox)) -* [Get started](https://developers.google.com/web/tools/workbox/guides/get-started) -* [Contribute](CONTRIBUTING.md) +- [Overview](https://developers.google.com/web/tools/workbox/) ([site source](https://github.com/google/WebFundamentals/tree/main/src/content/en/tools/workbox)) +- [Get started](https://developers.google.com/web/tools/workbox/guides/get-started) +- [Contribute](CONTRIBUTING.md) ## Contributing diff --git a/demos/src/workbox-background-sync-demo/index.html b/demos/src/workbox-background-sync-demo/index.html index af27e10fd..c36ea0cc7 100644 --- a/demos/src/workbox-background-sync-demo/index.html +++ b/demos/src/workbox-background-sync-demo/index.html @@ -2,30 +2,37 @@ workbox-background-sync demo - - - - - + + + + + -

workbox-background-sync Demo

@@ -33,37 +40,49 @@

workbox-background-sync Demo

    -
  1. Open DevTools.
  2. +
  3. + Open DevTools. +
  4. Switch to the Network panel.
  5. Toggle `Disable cache` checkbox on (it's unchecked by default).
  6. Click `Make Fetch request` button below.
  7. Observe that request is successfully completed with status 200.
  8. -
  9. Disconnect from actual network (DevTools offline doesn't work for background sync).
  10. +
  11. + Disconnect from actual network (DevTools offline doesn't work for + background sync). +
  12. Again, click `Make Fetch request` button below.
  13. Observe that request is aborted due to no network.
  14. -
  15. Connect to your network and observe the Network panel in DevTools.
  16. -
  17. Once the network is connected, you will see that the request is retried automatically upon the `sync` event.
  18. +
  19. + Connect to your network and observe the Network panel in DevTools. +
  20. +
  21. + Once the network is connected, you will see that the request is retried + automatically upon the `sync` event. +
-

- - - + +

+ - Back to Demos + Back to Demos +

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-background-sync-demo/package.json b/demos/src/workbox-background-sync-demo/package.json index 61ddddf5d..b8d4a9e63 100644 --- a/demos/src/workbox-background-sync-demo/package.json +++ b/demos/src/workbox-background-sync-demo/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-background-sync", - "version": "1.0.0", - "description": "Workbox Background Sync Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-background-sync", + "version": "1.0.0", + "description": "Workbox Background Sync Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-background-sync-demo/sw.js b/demos/src/workbox-background-sync-demo/sw.js index da074b9bd..45098b34b 100644 --- a/demos/src/workbox-background-sync-demo/sw.js +++ b/demos/src/workbox-background-sync-demo/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); // Note: Ignore the error that Glitch raises about workbox being undefined. workbox.setConfig({ @@ -6,13 +8,14 @@ workbox.setConfig({ }); const bgSyncPlugin = new workbox.backgroundSync.BackgroundSyncPlugin( - 'myQueueName'); + 'myQueueName', +); workbox.routing.registerRoute( - ({url}) => url.pathname === '/example.txt', - new workbox.strategies.NetworkOnly({ - plugins: [bgSyncPlugin], - }), + ({url}) => url.pathname === '/example.txt', + new workbox.strategies.NetworkOnly({ + plugins: [bgSyncPlugin], + }), ); workbox.core.skipWaiting(); diff --git a/demos/src/workbox-background-sync-demo/updateServer.js b/demos/src/workbox-background-sync-demo/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-background-sync-demo/updateServer.js +++ b/demos/src/workbox-background-sync-demo/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-broadcast-update-demo/index.html b/demos/src/workbox-broadcast-update-demo/index.html index 22ab3b36d..607bc56b2 100644 --- a/demos/src/workbox-broadcast-update-demo/index.html +++ b/demos/src/workbox-broadcast-update-demo/index.html @@ -2,31 +2,38 @@ workbox-broadcast-update demo - - - - - + + + + + - -
+

workbox-broadcast-update Demo

@@ -35,27 +42,30 @@

workbox-broadcast-update Demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click any of the buttons below and view the logs: +
  5. + Click any of the buttons below and view the logs:
      -
    • +
    • +

      + +

      +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-broadcast-update-demo/package.json b/demos/src/workbox-broadcast-update-demo/package.json index 8b3934168..0651ee960 100644 --- a/demos/src/workbox-broadcast-update-demo/package.json +++ b/demos/src/workbox-broadcast-update-demo/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-broadcast-update", - "version": "1.0.0", - "description": "Workbox Broadcast Update Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-broadcast-update", + "version": "1.0.0", + "description": "Workbox Broadcast Update Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-broadcast-update-demo/sw.js b/demos/src/workbox-broadcast-update-demo/sw.js index d650f98e2..54b4fbb38 100644 --- a/demos/src/workbox-broadcast-update-demo/sw.js +++ b/demos/src/workbox-broadcast-update-demo/sw.js @@ -1,12 +1,13 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, }); - const broadcastUpdate = new workbox.broadcastUpdate.BroadcastCacheUpdate( - 'broadcast-update-demo', + 'broadcast-update-demo', ); const initialResponse = new Response('Response 1', { diff --git a/demos/src/workbox-broadcast-update-demo/updateServer.js b/demos/src/workbox-broadcast-update-demo/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-broadcast-update-demo/updateServer.js +++ b/demos/src/workbox-broadcast-update-demo/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-cacheable-response/index.html b/demos/src/workbox-cacheable-response/index.html index b830dabda..a6c435893 100644 --- a/demos/src/workbox-cacheable-response/index.html +++ b/demos/src/workbox-cacheable-response/index.html @@ -2,31 +2,38 @@ workbox-cacheable-response demo - - - - - + + + + + - -
+

workbox-cacheable-response Demo

@@ -35,16 +42,34 @@

workbox-cacheable-response Demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click any of the buttons below and view the logs and network responses: +
  5. + Click any of the buttons below and view the logs and network responses:
      -
    • -
    • -
    • +
    • +

      + +

      +
    • +
    • +

      + +

      +
    • +
    • +

      + +

      +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-cacheable-response/package.json b/demos/src/workbox-cacheable-response/package.json index 464bb32db..b285fff05 100644 --- a/demos/src/workbox-cacheable-response/package.json +++ b/demos/src/workbox-cacheable-response/package.json @@ -13,4 +13,4 @@ "node": "8.x" }, "license": "MIT" -} \ No newline at end of file +} diff --git a/demos/src/workbox-cacheable-response/server.js b/demos/src/workbox-cacheable-response/server.js index c963ae2df..8600453d0 100644 --- a/demos/src/workbox-cacheable-response/server.js +++ b/demos/src/workbox-cacheable-response/server.js @@ -9,31 +9,28 @@ const app = express(); // but feel free to use whatever libs or frameworks you'd like through `package.json`. // http://expressjs.com/en/starter/basic-routing.html -app.get('/', function(request, response) { +app.get('/', function (request, response) { response.sendFile(__dirname + '/index.html'); }); -app.get('/sw.js', function(request, response) { +app.get('/sw.js', function (request, response) { response.sendFile(__dirname + '/sw.js'); }); // listen for requests :) -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); -app.get('/api/is-response-cacheable', - function(req, res) { - if (req.headers['x-is-cacheable']) { - const value = req.headers['x-is-cacheable']; - res.set('X-Is-Cacheable', value); - res.send(`This response has 'X-Is-Cacheable' header set to '${value}'`); - } else { - res.send(`This response has no 'X-Is-Cacheable' header`); - } - }, -); - +app.get('/api/is-response-cacheable', function (req, res) { + if (req.headers['x-is-cacheable']) { + const value = req.headers['x-is-cacheable']; + res.set('X-Is-Cacheable', value); + res.send(`This response has 'X-Is-Cacheable' header set to '${value}'`); + } else { + res.send(`This response has no 'X-Is-Cacheable' header`); + } +}); /* ///////////////////////////////////////////////////////////////////////////// The code below this comment is unrelated to the demo and used for maintenance @@ -53,7 +50,7 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); diff --git a/demos/src/workbox-cacheable-response/sw.js b/demos/src/workbox-cacheable-response/sw.js index d0047f007..9ce3dac38 100644 --- a/demos/src/workbox-cacheable-response/sw.js +++ b/demos/src/workbox-cacheable-response/sw.js @@ -1,10 +1,11 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, }); - const cacheable = new workbox.cacheableResponse.CacheableResponse({ statuses: [200], headers: { @@ -13,16 +14,15 @@ const cacheable = new workbox.cacheableResponse.CacheableResponse({ }); const handleCachableResponse = (event) => { - return fetch(event.request) - .then((response) => { - if (cacheable.isResponseCacheable(response)) { - console.log('Response meets the criteria'); - } else { - console.log('Response does NOT meet the criteria'); - } + return fetch(event.request).then((response) => { + if (cacheable.isResponseCacheable(response)) { + console.log('Response meets the criteria'); + } else { + console.log('Response does NOT meet the criteria'); + } - return response; - }); + return response; + }); }; self.addEventListener('fetch', (event) => { diff --git a/demos/src/workbox-core/index.html b/demos/src/workbox-core/index.html index 481f5324d..e723c15cb 100644 --- a/demos/src/workbox-core/index.html +++ b/demos/src/workbox-core/index.html @@ -2,31 +2,38 @@ workbox-core demo - - - - - + + + + + - -
+

workbox-core demo

@@ -35,12 +42,27 @@

workbox-core demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click this button:
  5. +
  6. + Click this button:
    +
  7. Checkout the logs for info on Workbox and getting started.
  8. -
  9. Click this button to print out various types of logs:
  10. -
  11. Click this button to print out the Workbox Cache Names:
  12. +
  13. + Click this button to print out various types of logs:
    +
  14. +
  15. + Click this button to print out the Workbox Cache Names:
    +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-core/package.json b/demos/src/workbox-core/package.json index b34c658c9..2c3034b14 100644 --- a/demos/src/workbox-core/package.json +++ b/demos/src/workbox-core/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-core", - "version": "1.0.0", - "description": "Workbox Core Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-core", + "version": "1.0.0", + "description": "Workbox Core Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-core/sw.js b/demos/src/workbox-core/sw.js index 53fedd866..d3b73087d 100644 --- a/demos/src/workbox-core/sw.js +++ b/demos/src/workbox-core/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); // Note: Ignore the error that Glitch raises about workbox being undefined. workbox.setConfig({ diff --git a/demos/src/workbox-core/updateServer.js b/demos/src/workbox-core/updateServer.js index c331be81e..b9d954534 100644 --- a/demos/src/workbox-core/updateServer.js +++ b/demos/src/workbox-core/updateServer.js @@ -28,12 +28,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-expiration/index.html b/demos/src/workbox-expiration/index.html index 80b104167..307581c46 100644 --- a/demos/src/workbox-expiration/index.html +++ b/demos/src/workbox-expiration/index.html @@ -2,66 +2,90 @@ workbox-expiration demo - - - - - + + + + + - -
+

workbox-expiration Demo

-
  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click the following buttons and look at the Cache and IndexedDB entries. +
  5. + Click the following buttons and look at the Cache and IndexedDB entries.
      -
    1. (Expires in: Not Added Yet)
    2. -
    3. (Expires in: Not Added Yet)
    4. -
    5. (Expires in: Not Added Yet)
    6. -
    7. (Expires in: Not Added Yet)
    8. -
    9. (Expires in: Not Added Yet)
    10. +
    11. + (Expires in: + Not Added Yet) +
    12. +
    13. + (Expires in: + Not Added Yet) +
    14. +
    15. + (Expires in: + Not Added Yet) +
    16. +
    17. + (Expires in: + Not Added Yet) +
    18. +
    19. + (Expires in: + Not Added Yet) +
  6. -
  7. To remove any expired entries click here:

  8. +
  9. + To remove any expired entries click here: +

    +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-expiration/package.json b/demos/src/workbox-expiration/package.json index 184e94665..565ccbc44 100644 --- a/demos/src/workbox-expiration/package.json +++ b/demos/src/workbox-expiration/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-expiration", - "version": "1.0.0", - "description": "Workbox Expiration Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-expiration", + "version": "1.0.0", + "description": "Workbox Expiration Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-expiration/sw.js b/demos/src/workbox-expiration/sw.js index 7e1f916c1..c57ffab80 100644 --- a/demos/src/workbox-expiration/sw.js +++ b/demos/src/workbox-expiration/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); // Note: Ignore the error that Glitch raises about workbox being undefined. workbox.setConfig({ @@ -6,17 +8,19 @@ workbox.setConfig({ }); const expirationManager = new workbox.expiration.CacheExpiration( - 'demo-cache-for-expiration', { - maxEntries: 3, - maxAgeSeconds: 30, - }); + 'demo-cache-for-expiration', + { + maxEntries: 3, + maxAgeSeconds: 30, + }, +); const updateEntry = async (entryID) => { const openCache = await caches.open('demo-cache-for-expiration'); openCache.put( - `example-entry-${entryID}`, - new Response(`Hello from entry number ${entryID}`), + `example-entry-${entryID}`, + new Response(`Hello from entry number ${entryID}`), ); expirationManager.updateTimestamp(`example-entry-${entryID}`); diff --git a/demos/src/workbox-expiration/updateServer.js b/demos/src/workbox-expiration/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-expiration/updateServer.js +++ b/demos/src/workbox-expiration/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-google-analytics/index.html b/demos/src/workbox-google-analytics/index.html index 829cde91b..23f847ee8 100644 --- a/demos/src/workbox-google-analytics/index.html +++ b/demos/src/workbox-google-analytics/index.html @@ -2,31 +2,38 @@ workbox-google-analytics demo - - - - - + + + + + - -
+

workbox-google-analytics Demo

@@ -35,19 +42,45 @@

workbox-google-analytics Demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click this button:

  5. -
  6. Turn off your machine's connection and press the button again. Of course, the requests fail
  7. -
  8. Upon reconnecting to the network, workbox-googleAnalytics will empty the request queue
  9. +
  10. + Click this button: +

    +
  11. +
  12. + Turn off your machine's connection and press the button again. Of + course, the requests fail +
  13. +
  14. + Upon reconnecting to the network, workbox-googleAnalytics will empty the + request queue +
- - + @@ -55,22 +88,21 @@

workbox-google-analytics Demo

- - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-google-analytics/package.json b/demos/src/workbox-google-analytics/package.json index 7151adf33..fd219b7ea 100644 --- a/demos/src/workbox-google-analytics/package.json +++ b/demos/src/workbox-google-analytics/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-google-analytics", - "version": "1.0.0", - "description": "Workbox Google Analytics Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-google-analytics", + "version": "1.0.0", + "description": "Workbox Google Analytics Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-google-analytics/sw.js b/demos/src/workbox-google-analytics/sw.js index 6ec8be3e0..6db861e09 100644 --- a/demos/src/workbox-google-analytics/sw.js +++ b/demos/src/workbox-google-analytics/sw.js @@ -1,10 +1,11 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, }); - workbox.googleAnalytics.initialize(); workbox.core.skipWaiting(); diff --git a/demos/src/workbox-google-analytics/updateServer.js b/demos/src/workbox-google-analytics/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-google-analytics/updateServer.js +++ b/demos/src/workbox-google-analytics/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-navigation-preload/index.html b/demos/src/workbox-navigation-preload/index.html index 45ba6cb3c..5c1644ce3 100644 --- a/demos/src/workbox-navigation-preload/index.html +++ b/demos/src/workbox-navigation-preload/index.html @@ -2,30 +2,37 @@ workbox-navigation-preload demo - - - - - + + + + + -

workbox-navigation-preload Demo

@@ -33,27 +40,31 @@

workbox-navigation-preload Demo

    -
  1. workbox-navigation-preload enables navigation preload in browsers that support it
  2. +
  3. + workbox-navigation-preload enables navigation preload in browsers that + support it +
  4. Open the dev tools console and reload this page
  5. -
  6. There should be two requests for the HTML document: one initiated by the service worker, and one by Preload
  7. +
  8. + There should be two requests for the HTML document: one initiated by the + service worker, and one by Preload +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-navigation-preload/package.json b/demos/src/workbox-navigation-preload/package.json index 696942e40..07fd53505 100644 --- a/demos/src/workbox-navigation-preload/package.json +++ b/demos/src/workbox-navigation-preload/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-navigation-preload", - "version": "1.0.0", - "description": "Workbox Navigation Preload Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-navigation-preload", + "version": "1.0.0", + "description": "Workbox Navigation Preload Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-navigation-preload/sw.js b/demos/src/workbox-navigation-preload/sw.js index ab8ce0d3b..486005ff2 100644 --- a/demos/src/workbox-navigation-preload/sw.js +++ b/demos/src/workbox-navigation-preload/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, diff --git a/demos/src/workbox-navigation-preload/updateServer.js b/demos/src/workbox-navigation-preload/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-navigation-preload/updateServer.js +++ b/demos/src/workbox-navigation-preload/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-precaching/index.html b/demos/src/workbox-precaching/index.html index d7cb25841..64454fb4f 100644 --- a/demos/src/workbox-precaching/index.html +++ b/demos/src/workbox-precaching/index.html @@ -2,73 +2,93 @@ workbox-precaching demo - - - - - + + + + + - -
+

workbox-precaching Demo

    -
  1. Open DevTools
  2. -
  3. Go to the Console
  4. -
  5. Click this button:
  6. -
  7. Checkout the logs for info on what was precached.
  8. -
  9. Explore Cache in the "Application" tab in DevTools. Note: You may need to right-click and refresh.
  10. -
  11. Click this button:
  12. -
  13. Check logs, cache to highlight the new, updated and deleted entry.
  14. +
  15. Open DevTools
  16. +
  17. Go to the Console
  18. +
  19. + Click this button:
    +
  20. +
  21. Checkout the logs for info on what was precached.
  22. +
  23. + Explore Cache in the "Application" tab in DevTools. + Note: You may need to right-click and refresh. +
  24. +
  25. + Click this button:
    +
  26. +
  27. + Check logs, cache to highlight the new, updated and deleted entry. +
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-precaching/package.json b/demos/src/workbox-precaching/package.json index ab3b6b625..f5b19e382 100644 --- a/demos/src/workbox-precaching/package.json +++ b/demos/src/workbox-precaching/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-precaching", - "version": "1.0.0", - "description": "Workbox Precaching Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-precaching", + "version": "1.0.0", + "description": "Workbox Precaching Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-precaching/sw-1.js b/demos/src/workbox-precaching/sw-1.js index 1c9d998cc..5e623ed9d 100644 --- a/demos/src/workbox-precaching/sw-1.js +++ b/demos/src/workbox-precaching/sw-1.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, diff --git a/demos/src/workbox-precaching/sw-2.js b/demos/src/workbox-precaching/sw-2.js index 98c9894b0..7dc2b23c3 100644 --- a/demos/src/workbox-precaching/sw-2.js +++ b/demos/src/workbox-precaching/sw-2.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, diff --git a/demos/src/workbox-precaching/updateServer.js b/demos/src/workbox-precaching/updateServer.js index 9aabe435a..d307c8def 100644 --- a/demos/src/workbox-precaching/updateServer.js +++ b/demos/src/workbox-precaching/updateServer.js @@ -34,12 +34,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-range-requests/index.html b/demos/src/workbox-range-requests/index.html index 846bc505c..47ecd2552 100644 --- a/demos/src/workbox-range-requests/index.html +++ b/demos/src/workbox-range-requests/index.html @@ -2,31 +2,38 @@ workbox-range-requests demo - - - - - + + + + + - -
+

workbox-range-requests Demo

@@ -35,41 +42,50 @@

workbox-range-requests Demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click this button to request range 1 - 4 of 'hello, world.':
  5. +
  6. + Click this button to request range 1 - 4 of 'hello, world.':
    +
  7. Checkout the logs for info on the range request that was handled.
- - - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-range-requests/package.json b/demos/src/workbox-range-requests/package.json index 0b07da2ec..862e8e232 100644 --- a/demos/src/workbox-range-requests/package.json +++ b/demos/src/workbox-range-requests/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-range-requests", - "version": "1.0.0", - "description": "Workbox Range Requests Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-range-requests", + "version": "1.0.0", + "description": "Workbox Range Requests Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-range-requests/sw.js b/demos/src/workbox-range-requests/sw.js index a62bad26d..b28a34c18 100644 --- a/demos/src/workbox-range-requests/sw.js +++ b/demos/src/workbox-range-requests/sw.js @@ -1,17 +1,17 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, }); workbox.routing.registerRoute( - new RegExp('/range-request-example'), - new workbox.strategies.CacheOnly({ - cacheName: 'range-requests-demo', - plugins: [ - new workbox.rangeRequests.RangeRequestsPlugin(), - ], - }), + new RegExp('/range-request-example'), + new workbox.strategies.CacheOnly({ + cacheName: 'range-requests-demo', + plugins: [new workbox.rangeRequests.RangeRequestsPlugin()], + }), ); workbox.core.skipWaiting(); diff --git a/demos/src/workbox-range-requests/updateServer.js b/demos/src/workbox-range-requests/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-range-requests/updateServer.js +++ b/demos/src/workbox-range-requests/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-routing/index.html b/demos/src/workbox-routing/index.html index 7e0873f41..eb5ce966d 100644 --- a/demos/src/workbox-routing/index.html +++ b/demos/src/workbox-routing/index.html @@ -2,65 +2,78 @@ workbox-precaching demo - - - - - + + + + + - -
+

workbox-routing Demo

- +
  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click this button:
  5. +
  6. + Click this button:
    +
  7. Refresh the page
  8. -
  9. Notice that the image '/public/demo-img.png' was routed and is now a party popper
  10. +
  11. + Notice that the image '/public/demo-img.png' was routed and is now a + party popper +
- - - -

+ - +

+ - Back to Demos + Back to Demos +

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-routing/package.json b/demos/src/workbox-routing/package.json index ebb7335aa..b52bcdaf7 100644 --- a/demos/src/workbox-routing/package.json +++ b/demos/src/workbox-routing/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-routing", - "version": "1.0.0", - "description": "Workbox Routing Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-routing", + "version": "1.0.0", + "description": "Workbox Routing Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-routing/sw.js b/demos/src/workbox-routing/sw.js index d2a3647a5..7d3dcb8c2 100644 --- a/demos/src/workbox-routing/sw.js +++ b/demos/src/workbox-routing/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, diff --git a/demos/src/workbox-routing/updateServer.js b/demos/src/workbox-routing/updateServer.js index 7a288f852..96df8704a 100644 --- a/demos/src/workbox-routing/updateServer.js +++ b/demos/src/workbox-routing/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-strategies/index.html b/demos/src/workbox-strategies/index.html index 24044bb25..30aa98fca 100644 --- a/demos/src/workbox-strategies/index.html +++ b/demos/src/workbox-strategies/index.html @@ -2,31 +2,38 @@ workbox-strategies demo - - - - - + + + + + - -
+

workbox-strategies Demo

@@ -35,74 +42,110 @@

workbox-strategies Demo

  1. Open DevTools
  2. Go to the Console
  3. -
  4. Click any of the buttons below and view the logs: +
  5. + Click any of the buttons below and view the logs:
    • This will attempt to get a request from an empty cache.

      -

      +

      + +

      +
    • +
    • +

      + +

      +
    • +
    • +

      + +

      +
    • +
    • +

      +
    • +
    • +

      + +

      +
    • +
    • +

      + +

      +
    • +
    • +

      + +

    • -
    • -
    • -
    • -
    • -
    • -
- - Back to Demos + Back to Demos

- - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

- \ No newline at end of file + diff --git a/demos/src/workbox-strategies/sw.js b/demos/src/workbox-strategies/sw.js index 9420c7717..e7cd4322d 100644 --- a/demos/src/workbox-strategies/sw.js +++ b/demos/src/workbox-strategies/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); // To avoid async issues, we load strategies before we call it in the event listener workbox.loadModule('workbox-strategies'); // Note: Ignore the error that Glitch raises about workbox being undefined. @@ -41,7 +43,7 @@ self.addEventListener('fetch', (event) => { } case '/stale-while-revalidate.txt': { const staleWhileRevalidate = - new workbox.strategies.StaleWhileRevalidate(); + new workbox.strategies.StaleWhileRevalidate(); event.respondWith(staleWhileRevalidate.handle({event, request})); break; } @@ -55,12 +57,11 @@ workbox.core.clientsClaim(); // Populate the cache to illustrate cache-only-populated-cache route self.addEventListener('install', (event) => { event.waitUntil( - caches.open(workbox.core.cacheNames.runtime) - .then((cache) => { - return cache.put( - new Request('/cache-only-populated-cache'), - new Response('Hello from the populated cache.'), - ); - }), + caches.open(workbox.core.cacheNames.runtime).then((cache) => { + return cache.put( + new Request('/cache-only-populated-cache'), + new Response('Hello from the populated cache.'), + ); + }), ); }); diff --git a/demos/src/workbox-strategies/updateServer.js b/demos/src/workbox-strategies/updateServer.js index a804c3ac3..6b95ffd20 100644 --- a/demos/src/workbox-strategies/updateServer.js +++ b/demos/src/workbox-strategies/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-streams/index.html b/demos/src/workbox-streams/index.html index e6fd6350c..5e31bd2f3 100644 --- a/demos/src/workbox-streams/index.html +++ b/demos/src/workbox-streams/index.html @@ -2,31 +2,38 @@ workbox-streams demo - - - - - + + + + + - -
+

workbox-workbox-streams Demo

@@ -36,15 +43,16 @@

workbox-workbox-streams Demo

  • Open DevTools
  • Go to the Console
  • - Click this button to add an iframe to this page, whose - body is created from multiple streamed sources:
    + Click this button to add an iframe to this page, whose body + is created from multiple streamed sources:
  • -
  • Checkout the logs for info on how the streamed response was generated.
  • +
  • + Checkout the logs for info on how the streamed response was generated. +
  • - -
    +
    - - Back to Demos + Back to Demos

    - - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

    - \ No newline at end of file + diff --git a/demos/src/workbox-streams/package.json b/demos/src/workbox-streams/package.json index 5c9748fee..e1257b19d 100644 --- a/demos/src/workbox-streams/package.json +++ b/demos/src/workbox-streams/package.json @@ -12,4 +12,4 @@ "node": "8.x" }, "license": "MIT" -} \ No newline at end of file +} diff --git a/demos/src/workbox-streams/server.js b/demos/src/workbox-streams/server.js index 2d89eb6f3..d6753070c 100644 --- a/demos/src/workbox-streams/server.js +++ b/demos/src/workbox-streams/server.js @@ -9,20 +9,20 @@ const app = express(); // but feel free to use whatever libs or frameworks you'd like through `package.json`. // http://expressjs.com/en/starter/basic-routing.html -app.get('/', function(request, response) { +app.get('/', function (request, response) { response.sendFile(__dirname + '/index.html'); }); -app.get('/sw.js', function(request, response) { +app.get('/sw.js', function (request, response) { response.sendFile(__dirname + '/sw.js'); }); // listen for requests :) -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); -app.get('/api/date', function(req, res) { +app.get('/api/date', function (req, res) { res.header('Content-Type', 'text/plain'); res.header('Cache-Control', 'no-cache'); res.send(`Received from the server at ${new Date().toLocaleString()}`); @@ -46,7 +46,7 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); diff --git a/demos/src/workbox-streams/sw.js b/demos/src/workbox-streams/sw.js index 1caa88ab6..646270ed0 100644 --- a/demos/src/workbox-streams/sw.js +++ b/demos/src/workbox-streams/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, @@ -9,13 +11,15 @@ const START_CACHE_KEY = 'start'; const END_CACHE_KEY = 'end'; self.addEventListener('install', (event) => { - event.waitUntil((async () => { - const cache = await caches.open(CACHE_NAME); - await Promise.all([ - cache.put(START_CACHE_KEY, new Response('')), - cache.put(END_CACHE_KEY, new Response('')), - ]); - })()); + event.waitUntil( + (async () => { + const cache = await caches.open(CACHE_NAME); + await Promise.all([ + cache.put(START_CACHE_KEY, new Response('')), + cache.put(END_CACHE_KEY, new Response('')), + ]); + })(), + ); }); // Use a stale-while-revalidate strategy as a source for part of the response. @@ -28,18 +32,16 @@ const streamsStrategy = workbox.streams.strategy([ () => caches.match(START_CACHE_KEY, {cacheName: CACHE_NAME}), () => `

    🎉 This iframe is composed of multiple streams.

    `, () => `

    Here's an API call, using a stale-while-revalidate strategy:

    `, - ({event}) => apiStrategy.handle({ - event: event, - request: new Request('/api/date'), - }), + ({event}) => + apiStrategy.handle({ + event: event, + request: new Request('/api/date'), + }), () => caches.match(END_CACHE_KEY, {cacheName: CACHE_NAME}), ]); // Once the strategy is configured, the actual routing looks clean. -workbox.routing.registerRoute( - new RegExp('iframe$'), - streamsStrategy, -); +workbox.routing.registerRoute(new RegExp('iframe$'), streamsStrategy); workbox.core.skipWaiting(); workbox.core.clientsClaim(); diff --git a/demos/src/workbox-sw/index.html b/demos/src/workbox-sw/index.html index 0b25964a7..839ee5c16 100644 --- a/demos/src/workbox-sw/index.html +++ b/demos/src/workbox-sw/index.html @@ -2,30 +2,37 @@ workbox-sw demo - - - - - + + + + + -

    workbox-sw demo

    @@ -34,14 +41,21 @@

    workbox-sw demo

    1. Open DevTools and go to the console
    2. -
    3. Click this button:
    4. +
    5. + Click this button:
      +
    6. You should see a workbox message appear
    7. -
    8. Refresh the page, go to the network tab, and check the "Size" of demo-img.png. It should read (ServiceWorker)
    9. +
    10. + Refresh the page, go to the network tab, and check the "Size" of + demo-img.png. It should read (ServiceWorker) +
    - - + +

    - - Back to Demos + Back to Demos +

    - - Docs | - GitHub | - @workboxjs - + Docs | + GitHub | + @workboxjs +

    diff --git a/demos/src/workbox-sw/package.json b/demos/src/workbox-sw/package.json index 99f328327..c52f27f94 100644 --- a/demos/src/workbox-sw/package.json +++ b/demos/src/workbox-sw/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-sw", - "version": "1.0.0", - "description": "Workbox SW Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-sw", + "version": "1.0.0", + "description": "Workbox SW Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-sw/sw.js b/demos/src/workbox-sw/sw.js index fa950b0f7..39b6ecf8a 100644 --- a/demos/src/workbox-sw/sw.js +++ b/demos/src/workbox-sw/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); // Note: Ignore the error that Glitch raises about workbox being undefined. workbox.setConfig({ @@ -11,19 +13,19 @@ workbox.precaching.precacheAndRoute([ // Demonstrates using default cache workbox.routing.registerRoute( - new RegExp('.*\\.(?:js)'), - new workbox.strategies.NetworkFirst(), + new RegExp('.*\\.(?:js)'), + new workbox.strategies.NetworkFirst(), ); // Demonstrates a custom cache name for a route. workbox.routing.registerRoute( - new RegExp('.*\\.(?:png|jpg|jpeg|svg|gif)'), - new workbox.strategies.CacheFirst({ - cacheName: 'image-cache', - plugins: [ - new workbox.expiration.ExpirationPlugin({ - maxEntries: 3, - }), - ], - }), + new RegExp('.*\\.(?:png|jpg|jpeg|svg|gif)'), + new workbox.strategies.CacheFirst({ + cacheName: 'image-cache', + plugins: [ + new workbox.expiration.ExpirationPlugin({ + maxEntries: 3, + }), + ], + }), ); diff --git a/demos/src/workbox-sw/updateServer.js b/demos/src/workbox-sw/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-sw/updateServer.js +++ b/demos/src/workbox-sw/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/demos/src/workbox-window/index.html b/demos/src/workbox-window/index.html index 7d1da6ece..ea54d2998 100644 --- a/demos/src/workbox-window/index.html +++ b/demos/src/workbox-window/index.html @@ -2,30 +2,37 @@ workbox-window demo - - - - - + + + + + -

    workbox-window Demo

    @@ -37,12 +44,10 @@

    workbox-window Demo

  • Open up DevTools and go to the console
  • - - - Back to Demos + Back to Demos

    - - Docs | - GitHub | - @workboxjs - - + Docs | + GitHub | + @workboxjs +

    - \ No newline at end of file + diff --git a/demos/src/workbox-window/package.json b/demos/src/workbox-window/package.json index dc37a006c..c2dc2c47e 100644 --- a/demos/src/workbox-window/package.json +++ b/demos/src/workbox-window/package.json @@ -1,15 +1,15 @@ { - "name": "workbox-window", - "version": "1.0.0", - "description": "Workbox Window Demo Git Listener", - "scripts": { - "start": "node updateServer.js" - }, - "dependencies": { - "express": "^4.17.1" - }, - "engines": { - "node": "8.x" - }, - "license": "MIT" - } \ No newline at end of file + "name": "workbox-window", + "version": "1.0.0", + "description": "Workbox Window Demo Git Listener", + "scripts": { + "start": "node updateServer.js" + }, + "dependencies": { + "express": "^4.17.1" + }, + "engines": { + "node": "8.x" + }, + "license": "MIT" +} diff --git a/demos/src/workbox-window/sw.js b/demos/src/workbox-window/sw.js index fa9b4b149..582fd9238 100644 --- a/demos/src/workbox-window/sw.js +++ b/demos/src/workbox-window/sw.js @@ -1,4 +1,6 @@ -importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js'); +importScripts( + 'https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js', +); workbox.setConfig({ debug: true, diff --git a/demos/src/workbox-window/updateServer.js b/demos/src/workbox-window/updateServer.js index 2cc1df17d..5a2158e28 100644 --- a/demos/src/workbox-window/updateServer.js +++ b/demos/src/workbox-window/updateServer.js @@ -30,12 +30,12 @@ app.post('/deploy', (request, response) => { const repoUrl = request.query.repo; execSync( - `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + + `git checkout -- ./ && git pull -X theirs ${repoUrl} ` + `glitch && refresh && git branch -D glitch`, ); response.status(200).send(); }); -const listener = app.listen(process.env.PORT, function() { +const listener = app.listen(process.env.PORT, function () { console.log('Your app is listening on port ' + listener.address().port); }); diff --git a/gulp-tasks/build-node-packages.js b/gulp-tasks/build-node-packages.js index b9be07ef7..148530da2 100644 --- a/gulp-tasks/build-node-packages.js +++ b/gulp-tasks/build-node-packages.js @@ -17,27 +17,27 @@ const packageRunner = require('./utils/package-runner'); async function buildNodePackage(packagePath) { const outputDirectory = upath.join( - packagePath, - constants.PACKAGE_BUILD_DIRNAME, + packagePath, + constants.PACKAGE_BUILD_DIRNAME, ); const configFile = upath.join( - __dirname, - 'utils', - 'node-projects-babel.config.json', + __dirname, + 'utils', + 'node-projects-babel.config.json', ); await execa( - 'babel', - [ - '--config-file', - configFile, - `${packagePath}/src`, - '--out-dir', - outputDirectory, - '--copy-files', - ], - {preferLocal: true}, + 'babel', + [ + '--config-file', + configFile, + `${packagePath}/src`, + '--out-dir', + outputDirectory, + '--copy-files', + ], + {preferLocal: true}, ); } @@ -49,7 +49,7 @@ async function generateWorkboxBuildJSONSchema(packagePath) { } const program = TJS.programFromConfig( - upath.join(packagePath, 'tsconfig.json'), + upath.join(packagePath, 'tsconfig.json'), ); const generator = TJS.buildGenerator(program, { noExtraProps: true, @@ -93,26 +93,29 @@ async function generateWorkboxBuildJSONSchema(packagePath) { // See https://github.com/GoogleChrome/workbox/issues/2901 if (schema.definitions.WorkboxPlugin) { for (const plugin of Object.keys( - schema.definitions.WorkboxPlugin.properties, + schema.definitions.WorkboxPlugin.properties, )) { schema.definitions.WorkboxPlugin.properties[plugin] = {}; } } await fse.writeJSON( - upath.join(packagePath, 'src', 'schema', `${optionType}.json`), - schema, - {spaces: 2}, + upath.join(packagePath, 'src', 'schema', `${optionType}.json`), + schema, + {spaces: 2}, ); } } module.exports = { build_node_packages: parallel( - packageRunner('build_node_packages', 'node', buildNodePackage), + packageRunner('build_node_packages', 'node', buildNodePackage), ), build_node_ts_packages: parallel( - packageRunner('build_node_ts_packages', 'node_ts', - generateWorkboxBuildJSONSchema), + packageRunner( + 'build_node_ts_packages', + 'node_ts', + generateWorkboxBuildJSONSchema, + ), ), }; diff --git a/gulp-tasks/build-packages.js b/gulp-tasks/build-packages.js index 98d592901..0bd8d4a7b 100644 --- a/gulp-tasks/build-packages.js +++ b/gulp-tasks/build-packages.js @@ -11,8 +11,10 @@ const del = require('del'); const fse = require('fs-extra'); const upath = require('upath'); -const {build_node_packages, build_node_ts_packages} = - require('./build-node-packages'); +const { + build_node_packages, + build_node_ts_packages, +} = require('./build-node-packages'); const {build_sw_packages} = require('./build-sw-packages'); const {build_window_packages} = require('./build-window-packages'); const {transpile_typescript} = require('./transpile-typescript'); @@ -52,20 +54,16 @@ async function cleanPackage(packagePath) { // Wrap this in a function since it's used multiple times. function cleanSequence() { - return parallel(packageRunner('build_packages_clean', 'all', - cleanPackage)); + return parallel(packageRunner('build_packages_clean', 'all', cleanPackage)); } module.exports = { build_packages_clean: cleanSequence(), build_packages: series( - // This needs to be a series, not in parallel, so that there isn't a - // race condition with the terser nameCache. - transpile_typescript, - series(build_sw_packages, build_window_packages), - parallel( - build_node_packages, - build_node_ts_packages, - ), + // This needs to be a series, not in parallel, so that there isn't a + // race condition with the terser nameCache. + transpile_typescript, + series(build_sw_packages, build_window_packages), + parallel(build_node_packages, build_node_ts_packages), ), }; diff --git a/gulp-tasks/build-sw-packages.js b/gulp-tasks/build-sw-packages.js index 8a2c1ae1e..47f8ddf68 100644 --- a/gulp-tasks/build-sw-packages.js +++ b/gulp-tasks/build-sw-packages.js @@ -62,10 +62,9 @@ function globals(moduleId) { // on the global scope (i.e. workbox.) try { const pkg = require(upath.join(packagePath, 'package.json')); - return [ - pkg.workbox.browserNamespace, - additionalNamespace, - ].filter((value) => (value && value.length > 0)).join('.'); + return [pkg.workbox.browserNamespace, additionalNamespace] + .filter((value) => value && value.length > 0) + .join('.'); } catch (err) { logHelper.error(`Unable to get browserNamespace for '${packageName}'`); throw err; @@ -75,7 +74,7 @@ function globals(moduleId) { // This ensures all workbox-* modules are treated as external and are // referenced as globals. function externalAndPure(importPath) { - return (importPath.indexOf('workbox-') === 0); + return importPath.indexOf('workbox-') === 0; } async function buildSWBundle(packagePath, buildType) { @@ -108,8 +107,10 @@ async function buildSWBundle(packagePath, buildType) { outputFilename += '.js'; const namespace = pkgJson.workbox.browserNamespace; - const outputDirectory = upath.join(packagePath, - constants.PACKAGE_BUILD_DIRNAME); + const outputDirectory = upath.join( + packagePath, + constants.PACKAGE_BUILD_DIRNAME, + ); const plugins = rollupHelper.getDefaultPlugins(buildType); @@ -121,8 +122,10 @@ async function buildSWBundle(packagePath, buildType) { }, plugins, onwarn: (warning) => { - if (buildType === constants.BUILD_TYPES.prod && - warning.code === 'UNUSED_EXTERNAL_IMPORT') { + if ( + buildType === constants.BUILD_TYPES.prod && + warning.code === 'UNUSED_EXTERNAL_IMPORT' + ) { // This can occur when using rollup-plugin-replace. logHelper.warn(`[${warning.code}] ${warning.message}`); return; @@ -130,8 +133,9 @@ async function buildSWBundle(packagePath, buildType) { // The final builds should have no warnings. if (warning.code && warning.message) { - throw new Error(`Unhandled Rollup Warning: [${warning.code}] ` + - `${warning.message}`); + throw new Error( + `Unhandled Rollup Warning: [${warning.code}] ` + `${warning.message}`, + ); } else { throw new Error(`Unhandled Rollup Warning: ${warning}`); } @@ -150,17 +154,23 @@ async function buildSWBundle(packagePath, buildType) { // This reads a little cleaner with a function to generate the sub-sequences. function swBundleSequence() { - const builds = Object.keys(constants.BUILD_TYPES).map((type) => packageRunner( - 'build_sw_packages_bundle', 'sw', buildSWBundle, - constants.BUILD_TYPES[type])); + const builds = Object.keys(constants.BUILD_TYPES).map((type) => + packageRunner( + 'build_sw_packages_bundle', + 'sw', + buildSWBundle, + constants.BUILD_TYPES[type], + ), + ); return series(builds); } module.exports = { build_sw_packages: series( - parallel(packageRunner('build_sw_packages_version_module', 'sw', - versionModule)), - swBundleSequence(), + parallel( + packageRunner('build_sw_packages_version_module', 'sw', versionModule), + ), + swBundleSequence(), ), }; diff --git a/gulp-tasks/build-window-packages.js b/gulp-tasks/build-window-packages.js index 9c59bbc33..12febbf2b 100644 --- a/gulp-tasks/build-window-packages.js +++ b/gulp-tasks/build-window-packages.js @@ -27,8 +27,10 @@ async function buildWindowBundle(packagePath, buildType) { throw new Error(`Could not find ${packageIndex}`); } - const outputDirectory = upath.join(packagePath, - constants.PACKAGE_BUILD_DIRNAME); + const outputDirectory = upath.join( + packagePath, + constants.PACKAGE_BUILD_DIRNAME, + ); const esmFilename = `${packageName}.${buildType.slice(0, 4)}.mjs`; const esmLegacyFilename = `${packageName}.${buildType.slice(0, 4)}.es5.mjs`; @@ -36,8 +38,10 @@ async function buildWindowBundle(packagePath, buildType) { const onwarn = (warning) => { // This can occur when using rollup-plugin-replace. - if (buildType === constants.BUILD_TYPES.prod && - warning.code === 'UNUSED_EXTERNAL_IMPORT') { + if ( + buildType === constants.BUILD_TYPES.prod && + warning.code === 'UNUSED_EXTERNAL_IMPORT' + ) { logHelper.warn(`[${warning.code}] ${warning.message}`); return; } @@ -92,17 +96,27 @@ async function buildWindowBundle(packagePath, buildType) { // This reads a little cleaner with a function to generate the sub-sequences. function windowBundleSequence() { - const builds = Object.keys(constants.BUILD_TYPES).map((type) => packageRunner( - 'build_window_packages_bundle', 'window', buildWindowBundle, - constants.BUILD_TYPES[type])); + const builds = Object.keys(constants.BUILD_TYPES).map((type) => + packageRunner( + 'build_window_packages_bundle', + 'window', + buildWindowBundle, + constants.BUILD_TYPES[type], + ), + ); return series(builds); } module.exports = { build_window_packages: series( - parallel(packageRunner('build_window_packages_version_module', 'window', - versionModule)), - windowBundleSequence(), + parallel( + packageRunner( + 'build_window_packages_version_module', + 'window', + versionModule, + ), + ), + windowBundleSequence(), ), }; diff --git a/gulp-tasks/build.js b/gulp-tasks/build.js index ad4202b55..38efb80b1 100644 --- a/gulp-tasks/build.js +++ b/gulp-tasks/build.js @@ -17,18 +17,26 @@ const {build_packages} = require('./build-packages'); // to add CDN details to workbox-sw. // Make sure this runs **before** build_lerna_bootstrap. async function build_update_cdn_details() { - const cdnDetails = await fse.readJSON(upath.join( - __dirname, '..', 'cdn-details.json', - )); + const cdnDetails = await fse.readJSON( + upath.join(__dirname, '..', 'cdn-details.json'), + ); const workboxBuildPath = upath.join( - __dirname, '..', 'packages', 'workbox-build'); + __dirname, + '..', + 'packages', + 'workbox-build', + ); const workboxBuildCdnDetailsPath = upath.join( - workboxBuildPath, 'src', 'cdn-details.json'); + workboxBuildPath, + 'src', + 'cdn-details.json', + ); - const workboxBuildPkg = await fse.readJSON(upath.join( - workboxBuildPath, 'package.json')); + const workboxBuildPkg = await fse.readJSON( + upath.join(workboxBuildPath, 'package.json'), + ); cdnDetails.latestVersion = workboxBuildPkg.version; @@ -43,8 +51,8 @@ async function build_lerna_bootstrap() { module.exports = { build: series( - build_update_cdn_details, - build_lerna_bootstrap, - build_packages, + build_update_cdn_details, + build_lerna_bootstrap, + build_packages, ), }; diff --git a/gulp-tasks/docs.js b/gulp-tasks/docs.js index 842487413..94281c1a9 100644 --- a/gulp-tasks/docs.js +++ b/gulp-tasks/docs.js @@ -25,8 +25,10 @@ async function docs_build() { ].join('&'); const params = [ - '-c', upath.join(__dirname, '..', 'jsdoc.conf'), - '-d', DOCS_DIRECTORY, + '-c', + upath.join(__dirname, '..', 'jsdoc.conf'), + '-d', + DOCS_DIRECTORY, ]; if (!(global.cliOptions && global.cliOptions.pretty)) { @@ -40,10 +42,17 @@ You can view a friendlier UI by running 'gulp docs --pretty' `); params.push( - '--template', upath.join( - __dirname, '..', 'infra', 'templates', 'reference-docs', 'jsdoc', - ), - '--query', queryString, + '--template', + upath.join( + __dirname, + '..', + 'infra', + 'templates', + 'reference-docs', + 'jsdoc', + ), + '--query', + queryString, ); } diff --git a/gulp-tasks/lint.js b/gulp-tasks/lint.js index acce4c952..6b7ec7f6d 100644 --- a/gulp-tasks/lint.js +++ b/gulp-tasks/lint.js @@ -10,19 +10,31 @@ const {parallel} = require('gulp'); const execa = require('execa'); async function lint_js() { - await execa('eslint', [ - '**/*.{js,mjs}', - '--config', 'javascript.eslintrc.js', - '--ignore-path', '.gitignore', - ], {preferLocal: true}); + await execa( + 'eslint', + [ + '**/*.{js,mjs}', + '--config', + 'javascript.eslintrc.js', + '--ignore-path', + '.gitignore', + ], + {preferLocal: true}, + ); } async function lint_ts() { - await execa('eslint', [ - '**/*.ts', - '--config', 'typescript.eslintrc.js', - '--ignore-path', '.gitignore', - ], {preferLocal: true}); + await execa( + 'eslint', + [ + '**/*.ts', + '--config', + 'typescript.eslintrc.js', + '--ignore-path', + '.gitignore', + ], + {preferLocal: true}, + ); } module.exports = { diff --git a/gulp-tasks/publish-github.js b/gulp-tasks/publish-github.js index f943a803a..769a53fbc 100644 --- a/gulp-tasks/publish-github.js +++ b/gulp-tasks/publish-github.js @@ -47,8 +47,7 @@ async function publish_github() { // Get all of the tags in the repo. const allTags = await githubHelper.getTags(); const taggedReleases = await githubHelper.getTaggedReleases(); - const tagsToBuild = filterTagsWithReleaseBundles(allTags, - taggedReleases); + const tagsToBuild = filterTagsWithReleaseBundles(allTags, taggedReleases); if (tagsToBuild.length === 0) { logHelper.log(`No tags missing from GitHub.`); @@ -56,8 +55,11 @@ async function publish_github() { } for (const tagToBuild of tagsToBuild) { - await handleGithubRelease(tagToBuild.name, tagToBuild.name, - taggedReleases[tagToBuild.name]); + await handleGithubRelease( + tagToBuild.name, + tagToBuild.name, + taggedReleases[tagToBuild.name], + ); } } diff --git a/gulp-tasks/publish-glitch.js b/gulp-tasks/publish-glitch.js index 68efc2141..13517817d 100644 --- a/gulp-tasks/publish-glitch.js +++ b/gulp-tasks/publish-glitch.js @@ -48,12 +48,18 @@ async function publish_glitch() { await execa('git', ['commit', `-m'Autocommit on ${new Date()}'`], { cwd: projectPath, }); - await execa('git', ['push', 'origin', 'glitch', '-f', '--set-upstream', - '--no-verify'], {cwd: projectPath}); + await execa( + 'git', + ['push', 'origin', 'glitch', '-f', '--set-upstream', '--no-verify'], + {cwd: projectPath}, + ); const deployURL = new URL(`https://${project}.glitch.me/deploy`); deployURL.searchParams.set('secret', process.env.GLITCH_WORKBOX_SECRET); - deployURL.searchParams.set('repo', `https://api.glitch.com/git/${project}`); + deployURL.searchParams.set( + 'repo', + `https://api.glitch.com/git/${project}`, + ); await execa('curl', ['-X', 'POST', deployURL.href]); } catch (error) { logHelper.error(`'${error}' occurred while processing ${project}.`); diff --git a/gulp-tasks/publish-lerna.js b/gulp-tasks/publish-lerna.js index 963c45c86..a2c6b71e7 100644 --- a/gulp-tasks/publish-lerna.js +++ b/gulp-tasks/publish-lerna.js @@ -17,8 +17,11 @@ async function publish_lerna() { // gulp publish --distTag=latest would be the most common. if (global.cliOptions.distTag) { - logHelper.log(ol`Using ${logHelper.highlight( - '--dist-tag=' + global.cliOptions.distTag)}`); + logHelper.log( + ol`Using ${logHelper.highlight( + '--dist-tag=' + global.cliOptions.distTag, + )}`, + ); options.push('--dist-tag', global.cliOptions.distTag); } else { throw new Error(ol`Please set the --distTag command line option, normally diff --git a/gulp-tasks/publish.js b/gulp-tasks/publish.js index d43da03fe..863b7459b 100644 --- a/gulp-tasks/publish.js +++ b/gulp-tasks/publish.js @@ -34,6 +34,14 @@ async function dist_tag_check() { } module.exports = { - publish: series(dist_tag_check, publish_sign_in_check, build_packages_clean, - publish_clean, test, publish_lerna, publish_github, publish_cdn), + publish: series( + dist_tag_check, + publish_sign_in_check, + build_packages_clean, + publish_clean, + test, + publish_lerna, + publish_github, + publish_cdn, + ), }; diff --git a/gulp-tasks/test-integration.js b/gulp-tasks/test-integration.js index e3263399c..a931c00aa 100644 --- a/gulp-tasks/test-integration.js +++ b/gulp-tasks/test-integration.js @@ -25,7 +25,7 @@ function runFiles(filePaths) { return new Promise((resolve, reject) => { const mocha = new Mocha({ - retries: (process.env.TRAVIS || process.env.GITHUB_ACTIONS) ? 4 : 1, + retries: process.env.TRAVIS || process.env.GITHUB_ACTIONS ? 4 : 1, timeout: 3 * 60 * 1000, }); @@ -34,7 +34,7 @@ function runFiles(filePaths) { } // Run the tests. - mocha.run(function(failureCount) { + mocha.run(function (failureCount) { if (failureCount > 0) { return reject(new Error(`${failureCount} tests failed.`)); } @@ -63,8 +63,9 @@ async function runTestSuite(testPath, nodeEnv, seleniumBrowser, webdriver) { webdriver, }; - const testFiles = glob.sync(upath.join(__dirname, '..', testPath, - 'test-*.js')); + const testFiles = glob.sync( + upath.join(__dirname, '..', testPath, 'test-*.js'), + ); await runFiles(testFiles); } finally { @@ -106,8 +107,9 @@ async function test_integration() { // Install the latest Chrome and Firefox webdrivers without referencing // package-lock.json, to ensure that they're up to date. - await execa('npm', ['install', '--no-save', 'chromedriver', 'geckodriver'], - {preferLocal: true}); + await execa('npm', ['install', '--no-save', 'chromedriver', 'geckodriver'], { + preferLocal: true, + }); logHelper.log(`Downloading browsers...`); const expiration = 24; diff --git a/gulp-tasks/test-node.js b/gulp-tasks/test-node.js index b1e9f1ddd..682748bab 100644 --- a/gulp-tasks/test-node.js +++ b/gulp-tasks/test-node.js @@ -28,14 +28,20 @@ async function runNodeTestSuite(testPath, nodeEnv) { process.env.NODE_ENV = nodeEnv; try { - const {stdout} = await execa('nyc', [ - '--clean', 'false', - '--silent', - 'mocha', - '--timeout', '60000', - `${testPath}/**/*.{js,mjs}`, - ...options, - ], {preferLocal: true}); + const {stdout} = await execa( + 'nyc', + [ + '--clean', + 'false', + '--silent', + 'mocha', + '--timeout', + '60000', + `${testPath}/**/*.{js,mjs}`, + ...options, + ], + {preferLocal: true}, + ); console.log(stdout); } finally { @@ -45,9 +51,7 @@ async function runNodeTestSuite(testPath, nodeEnv) { async function runNodeTestsWithEnv(testGroup, nodeEnv) { const globConfig = { - ignore: [ - '**/all/**', - ], + ignore: ['**/all/**'], }; if (testGroup === 'all') { @@ -87,17 +91,14 @@ async function test_node_coverage() { const runOptions = []; if (global.packageOrStar !== '*') { runOptions.push('--include'); - runOptions.push( - upath.join('packages', global.packageOrStar, '**', '*'), - ); + runOptions.push(upath.join('packages', global.packageOrStar, '**', '*')); } - const {stdout} = await execa('nyc', [ - 'report', - '--reporter', 'lcov', - '--reporter', 'text', - ...runOptions, - ], {preferLocal: true}); + const {stdout} = await execa( + 'nyc', + ['report', '--reporter', 'lcov', '--reporter', 'text', ...runOptions], + {preferLocal: true}, + ); console.log(stdout); } @@ -107,6 +108,11 @@ module.exports = { test_node_coverage, test_node_dev, test_node_prod, - test_node: series(test_node_clean, test_node_dev, test_node_prod, - test_node_all, test_node_coverage), + test_node: series( + test_node_clean, + test_node_dev, + test_node_prod, + test_node_all, + test_node_coverage, + ), }; diff --git a/gulp-tasks/test-server.js b/gulp-tasks/test-server.js index 730b66e19..27a0ed0c4 100644 --- a/gulp-tasks/test-server.js +++ b/gulp-tasks/test-server.js @@ -8,8 +8,10 @@ const {series} = require('gulp'); -const {transpile_typescript, transpile_typescript_watch} = - require('./transpile-typescript'); +const { + transpile_typescript, + transpile_typescript_watch, +} = require('./transpile-typescript'); const constants = require('./utils/constants'); const testServer = require('../infra/testing/server/index'); @@ -36,6 +38,9 @@ function startServer() { } module.exports = { - test_server: series(transpile_typescript, startServer, - transpile_typescript_watch), + test_server: series( + transpile_typescript, + startServer, + transpile_typescript_watch, + ), }; diff --git a/gulp-tasks/transpile-typescript.js b/gulp-tasks/transpile-typescript.js index 763fee6ca..53fe61b8d 100644 --- a/gulp-tasks/transpile-typescript.js +++ b/gulp-tasks/transpile-typescript.js @@ -72,10 +72,7 @@ async function transpile_typescript() { await execa('tsc', ['--build', 'tsconfig.json'], {preferLocal: true}); const jsFiles = await globby(`packages/*/**/*.js`, { - ignore: [ - '**/build/**', - '**/src/**', - ], + ignore: ['**/build/**', '**/src/**'], }); for (const jsFile of jsFiles) { diff --git a/gulp-tasks/utils/analyse-properties.js b/gulp-tasks/utils/analyse-properties.js index 2ce60b967..0e42e264a 100644 --- a/gulp-tasks/utils/analyse-properties.js +++ b/gulp-tasks/utils/analyse-properties.js @@ -30,21 +30,30 @@ const logHelper = require('../../infra/utils/log-helper'); class AnalyseBuildForProperties { run() { const filePaths = this.getBuildFiles(); - return Promise.all(filePaths.map((filePath) => { - const rawAnalysis = this.analyzeFile(filePath); - const analysis = this.tidyData(rawAnalysis); - - return { - filePath, - analysis, - }; - })); + return Promise.all( + filePaths.map((filePath) => { + const rawAnalysis = this.analyzeFile(filePath); + const analysis = this.tidyData(rawAnalysis); + + return { + filePath, + analysis, + }; + }), + ); } getBuildFiles() { // workbox-sw doesn't include .prod. in the build name. - const buildGlob = path.join(__dirname, '..', '..', 'packages', - '*', constants.PACKAGE_BUILD_DIRNAME, '{*.prod.js,workbox-sw.js}'); + const buildGlob = path.join( + __dirname, + '..', + '..', + 'packages', + '*', + constants.PACKAGE_BUILD_DIRNAME, + '{*.prod.js,workbox-sw.js}', + ); return glob.sync(buildGlob); } @@ -76,23 +85,24 @@ class AnalyseBuildForProperties { } tidyData(analysisEntries) { - return analysisEntries.filter((entry) => { - // If there is only one entry or it's a single character it's - // either not important or it's already been minified. - return entry.propertyCount > 1 && entry.propertyName.length > 1; - }) - .filter((entry) => { - switch (entry.propertyName) { - case 'await': - case 'async': - return false; - default: - return true; - } - }) - .sort((a, b) => { - return b.propertyCount - a.propertyCount; - }); + return analysisEntries + .filter((entry) => { + // If there is only one entry or it's a single character it's + // either not important or it's already been minified. + return entry.propertyCount > 1 && entry.propertyName.length > 1; + }) + .filter((entry) => { + switch (entry.propertyName) { + case 'await': + case 'async': + return false; + default: + return true; + } + }) + .sort((a, b) => { + return b.propertyCount - a.propertyCount; + }); } printDetails({filePath, analysis}) { @@ -110,8 +120,9 @@ class AnalyseBuildForProperties { analysis.forEach((entry) => { const numberOfSpaces = longestPropertyName - entry.propertyName.length; const extraSpace = ' '.repeat(numberOfSpaces); - logHelper.log(` ${entry.propertyName} ` + - `${extraSpace} ${entry.propertyCount}`); + logHelper.log( + ` ${entry.propertyName} ` + `${extraSpace} ${entry.propertyCount}`, + ); }); logHelper.log(); } diff --git a/gulp-tasks/utils/cdn-helper.js b/gulp-tasks/utils/cdn-helper.js index 91a2acf9e..1e1385af4 100644 --- a/gulp-tasks/utils/cdn-helper.js +++ b/gulp-tasks/utils/cdn-helper.js @@ -64,8 +64,9 @@ class CDNHelper { const bucket = gcs.bucket(cdnDetails.bucketName); for (const filePath of filePaths) { - const destination = - `${this._getReleaseTagPath(tagName)}/${path.basename(filePath)}`; + const destination = `${this._getReleaseTagPath(tagName)}/${path.basename( + filePath, + )}`; try { await bucket.upload(filePath, { @@ -82,7 +83,7 @@ class CDNHelper { throw err; } publicUrls.push( - `${cdnDetails.origin}/${cdnDetails.bucketName}/${destination}`, + `${cdnDetails.origin}/${cdnDetails.bucketName}/${destination}`, ); } diff --git a/gulp-tasks/utils/get-packages.js b/gulp-tasks/utils/get-packages.js index 6e8620930..3dd14009d 100644 --- a/gulp-tasks/utils/get-packages.js +++ b/gulp-tasks/utils/get-packages.js @@ -14,12 +14,14 @@ const DEFAULT_ROOT = path.join(__dirname, '..', '..'); const getPackages = ({type, root = DEFAULT_ROOT} = {}) => { const pathToPkgJsons = glob.sync('packages/*/package.json', {cwd: root}); - return pathToPkgJsons.map((pathToPkgJson) => { - const pkg = require(`${path.resolve(root)}/${pathToPkgJson}`); - return pkg; - }).filter((pkg) => { - return pkg.workbox && pkg.workbox.packageType === type; - }); + return pathToPkgJsons + .map((pathToPkgJson) => { + const pkg = require(`${path.resolve(root)}/${pathToPkgJson}`); + return pkg; + }) + .filter((pkg) => { + return pkg.workbox && pkg.workbox.packageType === type; + }); }; module.exports = { diff --git a/gulp-tasks/utils/github-helper.js b/gulp-tasks/utils/github-helper.js index 45af357db..59cbc90fc 100644 --- a/gulp-tasks/utils/github-helper.js +++ b/gulp-tasks/utils/github-helper.js @@ -18,8 +18,10 @@ const github = new GitHubApi(); // See https://github.com/mikedeboer/node-github#authentication const authenticate = () => { if (!process.env.GITHUB_TOKEN) { - throw new Error('You must set a GITHUB_TOKEN in your environment to ' + - 'publish a GitHub release.'); + throw new Error( + 'You must set a GITHUB_TOKEN in your environment to ' + + 'publish a GitHub release.', + ); } github.authenticate({ diff --git a/gulp-tasks/utils/node-projects-babel.config.json b/gulp-tasks/utils/node-projects-babel.config.json index e05f84c54..872dc8be2 100644 --- a/gulp-tasks/utils/node-projects-babel.config.json +++ b/gulp-tasks/utils/node-projects-babel.config.json @@ -1,5 +1,3 @@ { - "presets": [ - ["@babel/preset-env", {"targets": {"node": "10.0"}}] - ] + "presets": [["@babel/preset-env", {"targets": {"node": "10.0"}}]] } diff --git a/gulp-tasks/utils/output-filename-to-package-map.js b/gulp-tasks/utils/output-filename-to-package-map.js index c0049b901..0a1d741fe 100644 --- a/gulp-tasks/utils/output-filename-to-package-map.js +++ b/gulp-tasks/utils/output-filename-to-package-map.js @@ -8,10 +8,8 @@ const {getPackages} = require('./get-packages'); - const outputFilenameToPkgMap = {}; - const windowAndSWPackages = [ ...getPackages({type: 'sw'}), ...getPackages({type: 'window'}), diff --git a/gulp-tasks/utils/package-runner.js b/gulp-tasks/utils/package-runner.js index 96cfe533a..00e827ea7 100644 --- a/gulp-tasks/utils/package-runner.js +++ b/gulp-tasks/utils/package-runner.js @@ -18,20 +18,20 @@ const pkgPathToName = require('./pkg-path-to-name'); * @return Array Paths to package.json files for the matching packages. */ function getPackages(typeFilter) { - return glob.sync( - `packages/${global.packageOrStar}/package.json`, { - absolute: true, - }, - ).filter((pathToPackageJson) => { - const pkgInfo = require(pathToPackageJson); - const packageType = pkgInfo.workbox.packageType; - if (!packageType) { - throw Error(oneLine`Unable to determine package type. Please add + return glob + .sync(`packages/${global.packageOrStar}/package.json`, { + absolute: true, + }) + .filter((pathToPackageJson) => { + const pkgInfo = require(pathToPackageJson); + const packageType = pkgInfo.workbox.packageType; + if (!packageType) { + throw Error(oneLine`Unable to determine package type. Please add workbox.packageType metadata to ${pathToPackageJson}`); - } + } - return typeFilter === 'all' || typeFilter === packageType; - }); + return typeFilter === 'all' || typeFilter === packageType; + }); } /* diff --git a/gulp-tasks/utils/publish-helpers.js b/gulp-tasks/utils/publish-helpers.js index 2d70bcb46..659bb2575 100644 --- a/gulp-tasks/utils/publish-helpers.js +++ b/gulp-tasks/utils/publish-helpers.js @@ -31,7 +31,11 @@ const doesDirectoryExist = async (directoryPath) => { const getBuildPath = (tagName) => { const tempReleasePath = upath.join( - __dirname, '..', '..', constants.GENERATED_RELEASE_FILES_DIRNAME); + __dirname, + '..', + '..', + constants.GENERATED_RELEASE_FILES_DIRNAME, + ); return upath.join(tempReleasePath, tagName); }; @@ -54,8 +58,10 @@ const downloadGitCommit = async (tagName, gitBranch) => { await execa('git', [ 'clone', - '--branch', gitBranch, - '--depth', '1', + '--branch', + gitBranch, + '--depth', + '1', `http://github.com/${constants.GITHUB_OWNER}/${constants.GITHUB_REPO}.git`, sourceCodePath, ]); @@ -89,8 +95,10 @@ const buildGitCommit = async (tagName) => { * the folder structure will be the same. */ const groupBuildFiles = async (tagName, gitBranch) => { - const groupedBuildFiles = upath.join(getBuildPath(tagName), - GROUPED_BUILD_FILES); + const groupedBuildFiles = upath.join( + getBuildPath(tagName), + GROUPED_BUILD_FILES, + ); const dirExists = await doesDirectoryExist(groupedBuildFiles); if (!dirExists) { @@ -99,12 +107,17 @@ const groupBuildFiles = async (tagName, gitBranch) => { const sourceCodePath = upath.join(getBuildPath(tagName), SOURCE_CODE_DIR); - const browserPackages = Object.values(outputFilenameToPkgMap) - .map((item) => item.name); + const browserPackages = Object.values(outputFilenameToPkgMap).map( + (item) => item.name, + ); - const pattern = upath.join(sourceCodePath, 'packages', - `{${browserPackages.join(',')}}`, constants.PACKAGE_BUILD_DIRNAME, - '*.{js,mjs,map}'); + const pattern = upath.join( + sourceCodePath, + 'packages', + `{${browserPackages.join(',')}}`, + constants.PACKAGE_BUILD_DIRNAME, + '*.{js,mjs,map}', + ); logHelper.log(ol` Grouping Build Files into @@ -115,8 +128,9 @@ const groupBuildFiles = async (tagName, gitBranch) => { // directory. In others, have a flat file structure of just the built files. const filesToInclude = glob.sync(pattern); for (const fileToInclude of filesToInclude) { - await fse.copy(fileToInclude, upath.join(groupedBuildFiles, - upath.basename(fileToInclude)), + await fse.copy( + fileToInclude, + upath.join(groupedBuildFiles, upath.basename(fileToInclude)), ); } } else { diff --git a/gulp-tasks/utils/rollup-helper.js b/gulp-tasks/utils/rollup-helper.js index 1a87e2a9a..b84674c4a 100644 --- a/gulp-tasks/utils/rollup-helper.js +++ b/gulp-tasks/utils/rollup-helper.js @@ -27,19 +27,24 @@ module.exports = { const babelConfig = { babelHelpers: 'bundled', - presets: [['@babel/preset-env', { - loose: true, - targets: { - browsers: es5 ? - // If es5 is true, target IE11 - // https://github.com/browserslist/browserslist#queries - ['ie 11'] : - // This corresponds to the version of Chromium used by - // Samsung Internet 6.x, which is the minimum non-evergreen - // browser we currently support. - ['chrome >= 56'], - }, - }]], + presets: [ + [ + '@babel/preset-env', + { + loose: true, + targets: { + browsers: es5 + ? // If es5 is true, target IE11 + // https://github.com/browserslist/browserslist#queries + ['ie 11'] + : // This corresponds to the version of Chromium used by + // Samsung Internet 6.x, which is the minimum non-evergreen + // browser we currently support. + ['chrome >= 56'], + }, + }, + ], + ], }; if (es5) { babelConfig.plugins = [asyncToPromises]; @@ -78,8 +83,8 @@ module.exports = { // This is what the build should be const replaceOptions = { - 'preventAssignment': true, - 'WORKBOX_CDN_ROOT_URL': getVersionsCDNUrl(), + preventAssignment: true, + WORKBOX_CDN_ROOT_URL: getVersionsCDNUrl(), }; if (buildType) { diff --git a/gulp-tasks/utils/version-module.js b/gulp-tasks/utils/version-module.js index 8ad42c0ae..dffc2ad54 100644 --- a/gulp-tasks/utils/version-module.js +++ b/gulp-tasks/utils/version-module.js @@ -20,13 +20,16 @@ const getDetails = (packagePath) => { }; module.exports = async (packagePath) => { - const versionString = - `try{self['${getDetails(packagePath)}']&&_()}catch(e){}`; + const versionString = `try{self['${getDetails( + packagePath, + )}']&&_()}catch(e){}`; if (await fs.pathExists(path.join(packagePath, 'src', 'index.ts'))) { const tsVersionString = `// @ts-ignore\n${versionString}`; await fs.writeFile( - path.join(packagePath, 'src', '_version.ts'), tsVersionString); + path.join(packagePath, 'src', '_version.ts'), + tsVersionString, + ); } const mjsVersionString = `${versionString}// eslint-disable-line`; diff --git a/gulp-tasks/utils/versioned-cdn-url.js b/gulp-tasks/utils/versioned-cdn-url.js index b1d04bb26..7bb9bb51b 100644 --- a/gulp-tasks/utils/versioned-cdn-url.js +++ b/gulp-tasks/utils/versioned-cdn-url.js @@ -9,5 +9,5 @@ const cdn = require('../../packages/workbox-build/src/cdn-details.json'); const lernaPkg = require('../../lerna.json'); -module.exports = () => `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}` + - `/${lernaPkg.version}`; +module.exports = () => + `${cdn.origin}/${cdn.bucketName}/${cdn.releasesDir}` + `/${lernaPkg.version}`; diff --git a/gulpfile.js b/gulpfile.js index f1fc8eb00..22d9cedac 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -35,8 +35,10 @@ for (const taskFile of taskFiles) { continue; } if (name in module.exports) { - throw new Error(`Duplicate task definition: ${name} defined in` + - ` ${taskFile} conflicts with another task.`); + throw new Error( + `Duplicate task definition: ${name} defined in` + + ` ${taskFile} conflicts with another task.`, + ); } module.exports[name] = task; } diff --git a/infra/pr-bot/aggregate-size-plugin.js b/infra/pr-bot/aggregate-size-plugin.js index 0a462a6e3..d255dd238 100644 --- a/infra/pr-bot/aggregate-size-plugin.js +++ b/infra/pr-bot/aggregate-size-plugin.js @@ -69,7 +69,8 @@ class AggregateSizePlugin extends PluginInterface { const failPR = Boolean(percentValue > 100); - const prettyLog = `**${totalGzipString}** gzip'ed ` + + const prettyLog = + `**${totalGzipString}** gzip'ed ` + `(**${percentString}%** of limit)\n` + `**${totalSizeString}** uncompressed`; diff --git a/infra/templates/reference-docs/jsdoc/lang/en.yaml b/infra/templates/reference-docs/jsdoc/lang/en.yaml index ef31e60eb..8dc729e80 100644 --- a/infra/templates/reference-docs/jsdoc/lang/en.yaml +++ b/infra/templates/reference-docs/jsdoc/lang/en.yaml @@ -6,46 +6,46 @@ # https://opensource.org/licenses/MIT. constructor: - prefix: 'new ' + prefix: 'new ' returnTypesSeparator: ' returns ' tables: - body: - defaultValue: 'Defaults to {valueString}.' - defaultValueString: '{value}' - eachValueHasProperties: 'Values in {name} have the following properties:' - isOptional: 'Optional' - isRequired: ' ' - nonNullable: - long: 'Value must not be null.' - short: 'non-null' - nullable: - long: 'Value may be null.' - short: 'nullable' - repeatable: - long: 'Value may be repeated.' - short: 'repeatable' - unknownType: '?' - emptyCellPlaceholder: ' ' - header: - description: 'Description' - name: 'Name' - optional: 'Optional' - type: 'Type' - notApplicable: '—' + body: + defaultValue: 'Defaults to {valueString}.' + defaultValueString: '{value}' + eachValueHasProperties: 'Values in {name} have the following properties:' + isOptional: 'Optional' + isRequired: ' ' + nonNullable: + long: 'Value must not be null.' + short: 'non-null' + nullable: + long: 'Value may be null.' + short: 'nullable' + repeatable: + long: 'Value may be repeated.' + short: 'repeatable' + unknownType: '?' + emptyCellPlaceholder: ' ' + header: + description: 'Description' + name: 'Name' + optional: 'Optional' + type: 'Type' + notApplicable: '—' params: - all: '({params})' - joiner: | - {items, plural, - =0 {{param}} - other {, {param}}} - optional: '{param}' - repeatable: '...{param}' + all: '({params})' + joiner: | + {items, plural, + =0 {{param}} + other {, {param}}} + optional: '{param}' + repeatable: '...{param}' headings: - enums: | - {items, plural, - =1 {Enumeration} - other {Enumerations}} - values: | - {items, plural, - =1 {Value} - other {Values}} + enums: | + {items, plural, + =1 {Enumeration} + other {Enumerations}} + values: | + {items, plural, + =1 {Value} + other {Values}} diff --git a/infra/templates/reference-docs/jsdoc/lib/publishjob.js b/infra/templates/reference-docs/jsdoc/lib/publishjob.js index 47a3a7413..699c2a4b5 100755 --- a/infra/templates/reference-docs/jsdoc/lib/publishjob.js +++ b/infra/templates/reference-docs/jsdoc/lib/publishjob.js @@ -20,7 +20,7 @@ class PublishJob extends BaselinePublishJob { } generateTocYaml(symbols, basepath) { - symbols.sort(function(a, b) { + symbols.sort(function (a, b) { let aName = a.kind === 'namespace' ? a.longname : a.name; let bName = b.kind === 'namespace' ? b.longname : b.name; @@ -40,8 +40,8 @@ class PublishJob extends BaselinePublishJob { // check for duplicated names symbols.forEach((symbol) => { - const symbolName = symbol.kind === 'namespace' ? - symbol.longname : symbol.name; + const symbolName = + symbol.kind === 'namespace' ? symbol.longname : symbol.name; if ({}.hasOwnProperty.call(this._symbolNames, symbolName)) { this._symbolNames[symbolName] = true; } else { @@ -54,8 +54,8 @@ class PublishJob extends BaselinePublishJob { // disambiguated names are bar.Quxand baz.Qux. symbols.forEach((symbol) => { let mappedName = null; - const symbolName = symbol.kind === 'namespace' ? - symbol.longname : symbol.name; + const symbolName = + symbol.kind === 'namespace' ? symbol.longname : symbol.name; if (this._symbolNames[symbolName] === true) { if (symbol.kind !== 'namespace') { @@ -69,8 +69,9 @@ class PublishJob extends BaselinePublishJob { } } - symbol.tocYamlName = mappedName || (symbol.kind === 'namespace' ? - symbol.longname : symbol.name); + symbol.tocYamlName = + mappedName || + (symbol.kind === 'namespace' ? symbol.longname : symbol.name); }); const data = { @@ -98,8 +99,7 @@ class PublishJob extends BaselinePublishJob { longnames.sort(); const data = { longnames: longnames, - pageTitle: global.env.opts.query ? - global.env.opts.query.productName : '', + pageTitle: global.env.opts.query ? global.env.opts.query.productName : '', }; this.generate('index-all', data, 'index-all.html'); diff --git a/infra/templates/reference-docs/jsdoc/publish.js b/infra/templates/reference-docs/jsdoc/publish.js index 2c1fe3996..1814e6530 100644 --- a/infra/templates/reference-docs/jsdoc/publish.js +++ b/infra/templates/reference-docs/jsdoc/publish.js @@ -13,13 +13,14 @@ const fileFinder = require('jsdoc-baseline/lib/filefinder'); const helper = require('jsdoc/util/templateHelper'); const path = require('jsdoc/path'); -exports.publish = function(data, opts, tutorials) { +exports.publish = function (data, opts, tutorials) { baselineConfig.loadSync(); - baselineConfig.set('l10n', path.join(__dirname, 'lang')) - .set('static', path.join(__dirname, 'static')) - .set('views.partials', path.join(__dirname, 'views')) - .set('views.layouts', path.join(__dirname, 'views')) - .set('modules', path.join(__dirname, 'lib')); + baselineConfig + .set('l10n', path.join(__dirname, 'lang')) + .set('static', path.join(__dirname, 'static')) + .set('views.partials', path.join(__dirname, 'views')) + .set('views.layouts', path.join(__dirname, 'views')) + .set('modules', path.join(__dirname, 'lib')); const config = baselineConfig.get(); @@ -39,38 +40,44 @@ exports.publish = function(data, opts, tutorials) { docletHelper.addDoclets(data); - job.setPackage(docletHelper.getPackage()) - .setNavTree(docletHelper.navTree) - .setAllLongnamesTree(docletHelper.allLongnamesTree); + job + .setPackage(docletHelper.getPackage()) + .setNavTree(docletHelper.navTree) + .setAllLongnamesTree(docletHelper.allLongnamesTree); // create the output directory so we can start generating files - job.createOutputDirectory() - // then generate the source files so we can link to them - .generateSourceFiles(docletHelper.shortPaths); + job + .createOutputDirectory() + // then generate the source files so we can link to them + .generateSourceFiles(docletHelper.shortPaths); // generate globals page if necessary job.generateGlobals(docletHelper.globals); // generate TOC data and index page - job.generateTocData({hasGlobals: docletHelper.hasGlobals()}) - .generateIndex(opts.readme); + job + .generateTocData({hasGlobals: docletHelper.hasGlobals()}) + .generateIndex(opts.readme); // generate the rest of the output files (excluding tutorials) - docletHelper.getOutputLongnames().forEach(function(longname) { - job.generateByLongname(longname, docletHelper.getLongname(longname), - docletHelper.getMemberof(longname)); + docletHelper.getOutputLongnames().forEach(function (longname) { + job.generateByLongname( + longname, + docletHelper.getLongname(longname), + docletHelper.getMemberof(longname), + ); }); // finally, generate the tutorials, and copy static files to the output // directory - job.generateTutorials(tutorials) - .copyStaticFiles(); + job.generateTutorials(tutorials).copyStaticFiles(); // custom Cast pages job.generateTocYaml( - docletHelper.getCategory('classes') - .concat(docletHelper.getCategory('namespaces')) - .concat(docletHelper.getCategory('interfaces')), + docletHelper + .getCategory('classes') + .concat(docletHelper.getCategory('namespaces')) + .concat(docletHelper.getCategory('interfaces')), global.env.opts.query ? global.env.opts.query.basepath : '', ); job.generateIndexAll(Object.keys(docletHelper.longname)); diff --git a/infra/templates/reference-docs/jsdoc/static/jsdoc.css b/infra/templates/reference-docs/jsdoc/static/jsdoc.css index 1deb9cd59..012e37a7b 100644 --- a/infra/templates/reference-docs/jsdoc/static/jsdoc.css +++ b/infra/templates/reference-docs/jsdoc/static/jsdoc.css @@ -1,15 +1,14 @@ - .label { font-style: italic; text-transform: uppercase; } .dl-compact dt { - margin:8px 0px 0px 0px; + margin: 8px 0px 0px 0px; } h1.devsite-page-title { - display: none; + display: none; } h1 { @@ -67,5 +66,5 @@ h2.symbol-header { } table.function.param tr { - background: #80A7B9; + background: #80a7b9; } diff --git a/infra/testing/activate-and-control.js b/infra/testing/activate-and-control.js index 8385082b3..4221f3dce 100644 --- a/infra/testing/activate-and-control.js +++ b/infra/testing/activate-and-control.js @@ -14,59 +14,78 @@ module.exports = async (swURL) => { return activateSWSafari(swURL); } - const error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => { - function _onStateChangePromise(registration, desiredState) { - return new Promise((resolve, reject) => { - if (desiredState === 'activated' && registration.active) { - resolve(); - return; - } - - if (registration.installing === null) { - reject(new Error('No installing service worker found.')); - return; - } - - const serviceWorker = registration.installing; - - // We unregister all service workers after each test - this should - // always trigger an install state change - const stateChangeListener = (event) => { - if (event.target.state === desiredState) { - serviceWorker.removeEventListener('statechange', stateChangeListener); + const error = await global.__workbox.webdriver.executeAsyncScript( + (swURL, cb) => { + function _onStateChangePromise(registration, desiredState) { + return new Promise((resolve, reject) => { + if (desiredState === 'activated' && registration.active) { resolve(); return; } - if (event.target.state === 'redundant') { - serviceWorker.removeEventListener('statechange', stateChangeListener); - reject(new Error('Installing service worker became redundant.')); + if (registration.installing === null) { + reject(new Error('No installing service worker found.')); return; } - }; - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - } + const serviceWorker = registration.installing; - navigator.serviceWorker.register(swURL).then((registration) => { - return _onStateChangePromise(registration, 'activated'); - }).then(() => { - // Ensure the page is being controlled by the SW. - if (navigator.serviceWorker.controller && - navigator.serviceWorker.controller.scriptURL === swURL) { - return; - } else { - return new Promise((resolve) => { - navigator.serviceWorker.addEventListener('controllerchange', () => { - if (navigator.serviceWorker.controller.scriptURL === swURL) { + // We unregister all service workers after each test - this should + // always trigger an install state change + const stateChangeListener = (event) => { + if (event.target.state === desiredState) { + serviceWorker.removeEventListener( + 'statechange', + stateChangeListener, + ); resolve(); + return; + } + + if (event.target.state === 'redundant') { + serviceWorker.removeEventListener( + 'statechange', + stateChangeListener, + ); + reject(new Error('Installing service worker became redundant.')); + return; } - }); + }; + + serviceWorker.addEventListener('statechange', stateChangeListener); }); } - }).then(() => cb()).catch((error) => cb(error.message)); - }, swURL); + + navigator.serviceWorker + .register(swURL) + .then((registration) => { + return _onStateChangePromise(registration, 'activated'); + }) + .then(() => { + // Ensure the page is being controlled by the SW. + if ( + navigator.serviceWorker.controller && + navigator.serviceWorker.controller.scriptURL === swURL + ) { + return; + } else { + return new Promise((resolve) => { + navigator.serviceWorker.addEventListener( + 'controllerchange', + () => { + if (navigator.serviceWorker.controller.scriptURL === swURL) { + resolve(); + } + }, + ); + }); + } + }) + .then(() => cb()) + .catch((error) => cb(error.message)); + }, + swURL, + ); if (error) { throw new Error(error); diff --git a/infra/testing/activate-sw-safari.js b/infra/testing/activate-sw-safari.js index 78d259b96..eeb4d5238 100644 --- a/infra/testing/activate-sw-safari.js +++ b/infra/testing/activate-sw-safari.js @@ -9,49 +9,63 @@ // TODO(philipwalton): remove this in favor of using workbox-window. module.exports = async (swURL) => { // First step: Wait for the page to activate - let error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => { - const onStateChangePromise = (registration, desiredState) => { - return new Promise((resolve, reject) => { - if (desiredState === 'activated' && + let error = await global.__workbox.webdriver.executeAsyncScript( + (swURL, cb) => { + const onStateChangePromise = (registration, desiredState) => { + return new Promise((resolve, reject) => { + if ( + desiredState === 'activated' && registration.active && // Checking that the URLs match is needed to fix: // https://github.com/GoogleChrome/workbox/issues/1633 - registration.active.scriptURL === swURL) { - resolve(); - return; - } - - const serviceWorker = registration.installing || registration.waiting; - if (serviceWorker === null) { - throw new Error('There is no installing or waiting service worker.'); - } - - const stateChangeListener = function(evt) { - if (evt.target.state === desiredState) { - serviceWorker.removeEventListener('statechange', stateChangeListener); + registration.active.scriptURL === swURL + ) { resolve(); return; } - if (evt.target.state === 'redundant') { - serviceWorker.removeEventListener('statechange', stateChangeListener); - - // Must call reject rather than throw error here due to this - // being inside the scope of the callback function stateChangeListener - reject(new Error('The new service worker became redundant.')); - return; + const serviceWorker = registration.installing || registration.waiting; + if (serviceWorker === null) { + throw new Error( + 'There is no installing or waiting service worker.', + ); } - }; - serviceWorker.addEventListener('statechange', stateChangeListener); - }); - }; + const stateChangeListener = function (evt) { + if (evt.target.state === desiredState) { + serviceWorker.removeEventListener( + 'statechange', + stateChangeListener, + ); + resolve(); + return; + } - navigator.serviceWorker.register(swURL) + if (evt.target.state === 'redundant') { + serviceWorker.removeEventListener( + 'statechange', + stateChangeListener, + ); + + // Must call reject rather than throw error here due to this + // being inside the scope of the callback function stateChangeListener + reject(new Error('The new service worker became redundant.')); + return; + } + }; + + serviceWorker.addEventListener('statechange', stateChangeListener); + }); + }; + + navigator.serviceWorker + .register(swURL) .then((registration) => onStateChangePromise(registration, 'activated')) .then(() => cb()) .catch((err) => cb(err.message)); - }, swURL); + }, + swURL, + ); if (error) { throw error; @@ -59,13 +73,17 @@ module.exports = async (swURL) => { // To be 100% certain - ensure the SW is controlling the page. error = await global.__workbox.webdriver.executeAsyncScript((swURL, cb) => { - if (navigator.serviceWorker.controller && - navigator.serviceWorker.controller.scriptURL === swURL) { + if ( + navigator.serviceWorker.controller && + navigator.serviceWorker.controller.scriptURL === swURL + ) { cb(); } else if (!navigator.serviceWorker.controller) { cb(`There's no service worker controlling the page.`); } else { - cb(`There's an unexpected SW controlling the page: ${navigator.serviceWorker.controller.scriptURL}`); + cb( + `There's an unexpected SW controlling the page: ${navigator.serviceWorker.controller.scriptURL}`, + ); } }, swURL); diff --git a/infra/testing/auto-stub-logger.mjs b/infra/testing/auto-stub-logger.mjs index be0ec6bdb..b87ebc0bb 100644 --- a/infra/testing/auto-stub-logger.mjs +++ b/infra/testing/auto-stub-logger.mjs @@ -23,12 +23,12 @@ stubLogger(); // This is part of the "root" mocha suite - meaning it'll reset all the logger // values before every test. -beforeEach(function() { +beforeEach(function () { sandbox.restore(); stubLogger(); }); -after(function() { +after(function () { sandbox.restore(); }); diff --git a/infra/testing/clean-sw.js b/infra/testing/clean-sw.js index 54af4fa1f..5a5a9341e 100644 --- a/infra/testing/clean-sw.js +++ b/infra/testing/clean-sw.js @@ -17,11 +17,15 @@ module.exports = async (webdriver, testingURL) => { // can't call runInSW(). } const error = await webdriver.executeAsyncScript((cb) => { - navigator.serviceWorker.getRegistration().then((reg) => { - if (reg) { - return reg.unregister(); - } - }).then(() => cb()).catch((err) => cb(err.message)); + navigator.serviceWorker + .getRegistration() + .then((reg) => { + if (reg) { + return reg.unregister(); + } + }) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); diff --git a/infra/testing/comlink/node-interface.js b/infra/testing/comlink/node-interface.js index 96b73c9ea..3e20e4f7e 100644 --- a/infra/testing/comlink/node-interface.js +++ b/infra/testing/comlink/node-interface.js @@ -7,17 +7,23 @@ */ module.exports = async (command, ...args) => { - const result = await global.__workbox.webdriver.executeAsyncScript((command, args, cb) => { - if (!('_runInSW' in window)) { - cb({error: '_runInSW is not initialized.'}); - } else { - window._runInSW[command](...args) + const result = await global.__workbox.webdriver.executeAsyncScript( + (command, args, cb) => { + if (!('_runInSW' in window)) { + cb({error: '_runInSW is not initialized.'}); + } else { + window._runInSW[command](...args) .then((result) => cb(result)) - .catch((error) => cb({ - error: `While running ${command}(${args}): ${error.message}`, - })); - } - }, command, args); + .catch((error) => + cb({ + error: `While running ${command}(${args}): ${error.message}`, + }), + ); + } + }, + command, + args, + ); if (result instanceof Object && 'error' in result) { throw new Error(result.error); diff --git a/infra/testing/comlink/sw-interface.js b/infra/testing/comlink/sw-interface.js index 54739ec80..bc29996e2 100644 --- a/infra/testing/comlink/sw-interface.js +++ b/infra/testing/comlink/sw-interface.js @@ -42,12 +42,12 @@ const api = { const result = indexedDB.open(dbName); result.onsuccess = (event) => { const db = event.target.result; - db.transaction(objStoreName) - .objectStore(objStoreName) - .getAll() - .onsuccess = (event) => { - resolve(event.target.result); - }; + db + .transaction(objStoreName) + .objectStore(objStoreName) + .getAll().onsuccess = (event) => { + resolve(event.target.result); + }; }; }); }, diff --git a/infra/testing/comlink/window-interface.js b/infra/testing/comlink/window-interface.js index 964407c99..2e01255b5 100644 --- a/infra/testing/comlink/window-interface.js +++ b/infra/testing/comlink/window-interface.js @@ -8,7 +8,9 @@ function initComlink() { const channel = new MessageChannel(); - navigator.serviceWorker.controller.postMessage(channel.port2, [channel.port2]); + navigator.serviceWorker.controller.postMessage(channel.port2, [ + channel.port2, + ]); window._runInSW = Comlink.wrap(channel.port1); channel.port1.start(); } diff --git a/infra/testing/confirm-directory-contains.js b/infra/testing/confirm-directory-contains.js index 0faefb39c..0f14afc16 100644 --- a/infra/testing/confirm-directory-contains.js +++ b/infra/testing/confirm-directory-contains.js @@ -12,7 +12,8 @@ const upath = require('upath'); module.exports = async (directory, expectedContents) => { const relativeFiles = await globby('**', {cwd: directory}); - const absoluteFilesWithNativeSeparator = relativeFiles.map( - (file) => upath.resolve(directory, file).replace(/\//g, upath.sep)); + const absoluteFilesWithNativeSeparator = relativeFiles.map((file) => + upath.resolve(directory, file).replace(/\//g, upath.sep), + ); expect(absoluteFilesWithNativeSeparator).to.have.members(expectedContents); }; diff --git a/infra/testing/env-it.js b/infra/testing/env-it.js index 66e6f6e00..af6ef2070 100644 --- a/infra/testing/env-it.js +++ b/infra/testing/env-it.js @@ -8,11 +8,11 @@ module.exports = { devOnly: { - it: function(title, cb) { + it: function (title, cb) { // If the wrapped callback expects done, then we need to call it() with // a function that expects done. if (cb.length === 1) { - it(title, function(done) { + it(title, function (done) { if (process.env.NODE_ENV === 'production') { return this.skip(); } @@ -20,7 +20,7 @@ module.exports = { return cb(done); }); } else { - it(title, function() { + it(title, function () { if (process.env.NODE_ENV === 'production') { return this.skip(); } @@ -32,11 +32,11 @@ module.exports = { }, prodOnly: { - it: function(title, cb) { + it: function (title, cb) { // If the wrapped callback expects done, then we need to call it() with // a function that expects done. if (cb.length === 1) { - it(title, function(done) { + it(title, function (done) { if (process.env.NODE_ENV !== 'production') { return this.skip(); } @@ -44,7 +44,7 @@ module.exports = { return cb(done); }); } else { - it(title, function() { + it(title, function () { if (process.env.NODE_ENV !== 'production') { return this.skip(); } diff --git a/infra/testing/generate-variant-tests.js b/infra/testing/generate-variant-tests.js index 987ecf930..6f7e4cc20 100644 --- a/infra/testing/generate-variant-tests.js +++ b/infra/testing/generate-variant-tests.js @@ -26,13 +26,11 @@ const generateVariantTests = (itTitle, variants, func) => { variants.forEach((variant) => { // We are using function() {} here and NOT ARROW FUNCTIONS // to work with Mocha's binding for tests. - it(`${itTitle}. Variant: '${JSON.stringify(variant)}'`, - function() { - // Use .call to get the correct `this` binding needed by mocha. - // eslint-disable-next-line no-invalid-this - return func.call(this, variant); - }, - ); + it(`${itTitle}. Variant: '${JSON.stringify(variant)}'`, function () { + // Use .call to get the correct `this` binding needed by mocha. + // eslint-disable-next-line no-invalid-this + return func.call(this, variant); + }); }); }; diff --git a/infra/testing/helpers/compareResponses.mjs b/infra/testing/helpers/compareResponses.mjs index 9df5ac5b6..ce5658d03 100644 --- a/infra/testing/helpers/compareResponses.mjs +++ b/infra/testing/helpers/compareResponses.mjs @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - const compareResponses = async (first, second, shouldBeSame) => { const firstBody = await first.clone().text(); const secondBody = await second.clone().text(); @@ -18,6 +17,4 @@ const compareResponses = async (first, second, shouldBeSame) => { } }; -export { - compareResponses, -}; +export {compareResponses}; diff --git a/infra/testing/helpers/extendable-event-utils.mjs b/infra/testing/helpers/extendable-event-utils.mjs index 3835e0f81..9dc6b0a59 100644 --- a/infra/testing/helpers/extendable-event-utils.mjs +++ b/infra/testing/helpers/extendable-event-utils.mjs @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - const extendLifetimePromises = new WeakMap(); const eventResponses = new WeakMap(); @@ -14,7 +13,7 @@ export const eventDoneWaiting = async (event, {catchErrors = true} = {}) => { const promises = extendLifetimePromises.get(event); let promise; - while (promise = promises.shift()) { + while ((promise = promises.shift())) { // Ignore errors by default; if (catchErrors) { promise = promise.catch((e) => e); diff --git a/infra/testing/helpers/generateOpaqueResponse.mjs b/infra/testing/helpers/generateOpaqueResponse.mjs index f2105ad88..73c41c784 100644 --- a/infra/testing/helpers/generateOpaqueResponse.mjs +++ b/infra/testing/helpers/generateOpaqueResponse.mjs @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - // Cache a resonse value and clone it instead of re-fetching every time. let response; diff --git a/infra/testing/helpers/generateUniqueResponse.mjs b/infra/testing/helpers/generateUniqueResponse.mjs index a52513d18..be7ce3910 100644 --- a/infra/testing/helpers/generateUniqueResponse.mjs +++ b/infra/testing/helpers/generateUniqueResponse.mjs @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - let uid = 0; export const generateUniqueResponse = (responseInit = {}) => { diff --git a/infra/testing/server/index.js b/infra/testing/server/index.js index a8a4d7f0e..6884d08ac 100644 --- a/infra/testing/server/index.js +++ b/infra/testing/server/index.js @@ -45,9 +45,7 @@ function initApp() { } const staticDir = path.resolve(__dirname, '..', '..', '..'); - app.use( - express.static(staticDir), - serveIndex(staticDir, {'icons': true})); + app.use(express.static(staticDir), serveIndex(staticDir, {icons: true})); } function start() { diff --git a/infra/testing/server/routes/build-file.js b/infra/testing/server/routes/build-file.js index 62cba8dd0..38c3b491b 100644 --- a/infra/testing/server/routes/build-file.js +++ b/infra/testing/server/routes/build-file.js @@ -7,8 +7,9 @@ */ const path = require('path'); -const {outputFilenameToPkgMap} = require('../../../../gulp-tasks/utils/output-filename-to-package-map'); - +const { + outputFilenameToPkgMap, +} = require('../../../../gulp-tasks/utils/output-filename-to-package-map'); const match = '/__WORKBOX/buildFile/:packageFile'; @@ -17,7 +18,6 @@ async function handler(req, res) { const pkg = outputFilenameToPkgMap[packageFile.split('.')[0]]; const pkgDir = path.resolve('packages', pkg.name); - let file; if (packageFile.includes('.')) { file = path.join(pkgDir, 'build', packageFile); diff --git a/infra/testing/server/routes/sw-bundle.js b/infra/testing/server/routes/sw-bundle.js index ed70e33d6..c9e1eaaa6 100644 --- a/infra/testing/server/routes/sw-bundle.js +++ b/infra/testing/server/routes/sw-bundle.js @@ -7,7 +7,8 @@ */ const {getPackages} = require('../../../../gulp-tasks/utils/get-packages'); -const {needsTranspile, queueTranspile} = require('../../../../gulp-tasks/transpile-typescript').functions; +const {needsTranspile, queueTranspile} = + require('../../../../gulp-tasks/transpile-typescript').functions; const {nodeResolve} = require('@rollup/plugin-node-resolve'); const {rollup} = require('rollup'); const commonjs = require('@rollup/plugin-commonjs'); diff --git a/infra/testing/server/routes/templates-update.js b/infra/testing/server/routes/templates-update.js index 23a32b7f8..4eb835058 100644 --- a/infra/testing/server/routes/templates-update.js +++ b/infra/testing/server/routes/templates-update.js @@ -8,7 +8,6 @@ const templateData = require('../template-data'); - // An endpoint to update template data from within tests. Any JSON in the // POST body will be merged with the existing template data. const match = '/__WORKBOX/updateTemplate'; diff --git a/infra/testing/server/routes/templates.js b/infra/testing/server/routes/templates.js index b63753586..36c0bbb00 100644 --- a/infra/testing/server/routes/templates.js +++ b/infra/testing/server/routes/templates.js @@ -9,7 +9,6 @@ const path = require('path'); const templateData = require('../template-data'); - // Matches any URL ending in `.njk` and renders the file in the // `../templates/*` directory as the response. // NOTE: this allows you to serve a template file with any directory path, diff --git a/infra/testing/server/routes/test-sw.js b/infra/testing/server/routes/test-sw.js index 0a689cbf7..19d895067 100644 --- a/infra/testing/server/routes/test-sw.js +++ b/infra/testing/server/routes/test-sw.js @@ -10,7 +10,6 @@ const globby = require('globby'); const path = require('path'); const templateData = require('../template-data'); - const match = '/test/:packageName/sw/'; async function handler(req, res) { @@ -22,7 +21,8 @@ async function handler(req, res) { const {packageName} = req.params; const testFilter = req.query.filter || '**/test-*.mjs'; - const testFiles = await globby(`test/${packageName}/sw/${testFilter}`) || []; + const testFiles = + (await globby(`test/${packageName}/sw/${testFilter}`)) || []; const testModules = testFiles.map((file) => '/' + file); if (testFiles.length > 0) { diff --git a/infra/testing/server/routes/test-window.js b/infra/testing/server/routes/test-window.js index f5850830a..cc7c6932c 100644 --- a/infra/testing/server/routes/test-window.js +++ b/infra/testing/server/routes/test-window.js @@ -10,7 +10,6 @@ const globby = require('globby'); const path = require('path'); const templateData = require('../template-data'); - const match = '/test/:packageName/window/'; async function handler(req, res) { @@ -18,7 +17,7 @@ async function handler(req, res) { const testFilter = req.query.filter || '**/test-*.mjs'; const testFiles = - await globby(`test/${packageName}/window/**/${testFilter}`) || []; + (await globby(`test/${packageName}/window/**/${testFilter}`)) || []; const testModules = testFiles.map((file) => '/' + file); diff --git a/infra/testing/server/static/integration.html b/infra/testing/server/static/integration.html index 76fdd77dd..c31c82755 100644 --- a/infra/testing/server/static/integration.html +++ b/infra/testing/server/static/integration.html @@ -4,7 +4,7 @@

    You need to manually register the service worker.

    - + diff --git a/infra/testing/validator/service-worker-runtime.js b/infra/testing/validator/service-worker-runtime.js index 54bb05274..dd0896e2a 100644 --- a/infra/testing/validator/service-worker-runtime.js +++ b/infra/testing/validator/service-worker-runtime.js @@ -19,7 +19,9 @@ const {expect} = chai; // See https://github.com/chaijs/chai/issues/697 function stringifyFunctionsInArray(arr) { - return arr.map((item) => typeof item === 'function' ? item.toString() : item); + return arr.map((item) => + typeof item === 'function' ? item.toString() : item, + ); } function setupSpiesAndContextForInjectManifest() { @@ -76,10 +78,13 @@ function setupSpiesAndContextForInjectManifest() { }, }; - const context = Object.assign({ - importScripts, - workbox, - }, makeServiceWorkerEnv()); + const context = Object.assign( + { + importScripts, + workbox, + }, + makeServiceWorkerEnv(), + ); context.self.addEventListener = addEventListener; context.self.skipWaiting = sinon.spy(); @@ -128,13 +133,16 @@ function setupSpiesAndContextForGenerateSW() { skipWaiting: sinon.spy(), }; - const context = Object.assign({ - importScripts, - define: (_, scripts, callback) => { - importScripts(...scripts); - callback(workboxContext); + const context = Object.assign( + { + importScripts, + define: (_, scripts, callback) => { + importScripts(...scripts); + callback(workboxContext); + }, }, - }, makeServiceWorkerEnv()); + makeServiceWorkerEnv(), + ); context.self.addEventListener = addEventListener; context.self.skipWaiting = workboxContext.skipWaiting; @@ -144,14 +152,18 @@ function setupSpiesAndContextForGenerateSW() { function validateMethodCalls({methodsToSpies, expectedMethodCalls, context}) { for (const [method, spy] of Object.entries(methodsToSpies)) { if (spy.called) { - const args = spy.args.map( - (arg) => Array.isArray(arg) ? stringifyFunctionsInArray(arg) : arg); + const args = spy.args.map((arg) => + Array.isArray(arg) ? stringifyFunctionsInArray(arg) : arg, + ); - expect(args, `while testing method calls for ${method}`) - .to.matchPattern(expectedMethodCalls[method]); + expect(args, `while testing method calls for ${method}`).to.matchPattern( + expectedMethodCalls[method], + ); } else { - expect(expectedMethodCalls[method], - `while testing method calls for ${method}`).to.be.undefined; + expect( + expectedMethodCalls[method], + `while testing method calls for ${method}`, + ).to.be.undefined; } } @@ -159,7 +171,9 @@ function validateMethodCalls({methodsToSpies, expectedMethodCalls, context}) { // assignment, so we can't stub it out. if ('__WB_DISABLE_DEV_LOGS' in expectedMethodCalls) { expect(context.self.__WB_DISABLE_DEV_LOGS).to.eql( - expectedMethodCalls.__WB_DISABLE_DEV_LOGS, `__WB_DISABLE_DEV_LOGS`); + expectedMethodCalls.__WB_DISABLE_DEV_LOGS, + `__WB_DISABLE_DEV_LOGS`, + ); } } @@ -185,16 +199,19 @@ module.exports = async ({ swFile, swString, }) => { - assert((swFile || swString) && !(swFile && swString), - `Set swFile or swString, but not both.`); + assert( + (swFile || swString) && !(swFile && swString), + `Set swFile or swString, but not both.`, + ); if (swFile) { swString = await fse.readFile(swFile, 'utf8'); } - const {addEventListener, context, methodsToSpies} = entryPoint === 'injectManifest' ? - setupSpiesAndContextForInjectManifest() : - setupSpiesAndContextForGenerateSW(); + const {addEventListener, context, methodsToSpies} = + entryPoint === 'injectManifest' + ? setupSpiesAndContextForInjectManifest() + : setupSpiesAndContextForGenerateSW(); vm.runInNewContext(swString, context); diff --git a/infra/testing/webdriver/IframeManager.js b/infra/testing/webdriver/IframeManager.js index acd4dc4bd..a78b3944c 100644 --- a/infra/testing/webdriver/IframeManager.js +++ b/infra/testing/webdriver/IframeManager.js @@ -16,12 +16,16 @@ class Client { } async executeAsyncScript(code) { - const value = await this._driver.executeAsyncScript((id, code, cb) => { - const iframe = document.querySelector(`#${id}`); - Promise.resolve(iframe.contentWindow.eval(code)) + const value = await this._driver.executeAsyncScript( + (id, code, cb) => { + const iframe = document.querySelector(`#${id}`); + Promise.resolve(iframe.contentWindow.eval(code)) .then((value) => cb(value)) .catch((err) => cb(err.toString())); - }, this._id, code); + }, + this._id, + code, + ); return value; } @@ -54,19 +58,23 @@ class IframeManager { } async createIframeClient(url) { - const iframeId = await this._driver.executeAsyncScript((url, prefix, cb) => { - const el = document.createElement('iframe'); - if (!('iframeCount' in window)) { - window.iframeCount = 1; - } - const id = `${prefix}${window.iframeCount++}`; - el.addEventListener('load', () => { - cb(id); - }); - el.src = url; - el.id = id; - document.body.appendChild(el); - }, url, PREFIX); + const iframeId = await this._driver.executeAsyncScript( + (url, prefix, cb) => { + const el = document.createElement('iframe'); + if (!('iframeCount' in window)) { + window.iframeCount = 1; + } + const id = `${prefix}${window.iframeCount++}`; + el.addEventListener('load', () => { + cb(id); + }); + el.src = url; + el.id = id; + document.body.appendChild(el); + }, + url, + PREFIX, + ); return new Client(this._driver, iframeId); } diff --git a/infra/testing/webdriver/executeAsyncAndCatch.js b/infra/testing/webdriver/executeAsyncAndCatch.js index ae0c4acbd..dc17255ba 100644 --- a/infra/testing/webdriver/executeAsyncAndCatch.js +++ b/infra/testing/webdriver/executeAsyncAndCatch.js @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - // Store local references of these globals. const {webdriver} = global.__workbox; diff --git a/infra/testing/webdriver/runUnitTests.js b/infra/testing/webdriver/runUnitTests.js index 00bd8b575..99ace1276 100644 --- a/infra/testing/webdriver/runUnitTests.js +++ b/infra/testing/webdriver/runUnitTests.js @@ -8,7 +8,6 @@ const waitUntil = require('../wait-until'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; @@ -16,9 +15,13 @@ const runUnitTests = async (testPath) => { await webdriver.get(server.getAddress() + testPath); // Wait until the mocha tests are finished. - await waitUntil(async () => { - return await webdriver.executeScript(() => self.mochaResults); - }, 120, 500); // Retry for 60 seconds. + await waitUntil( + async () => { + return await webdriver.executeScript(() => self.mochaResults); + }, + 120, + 500, + ); // Retry for 60 seconds. const results = await webdriver.executeScript(() => self.mochaResults); diff --git a/infra/testing/webdriver/unregisterAllSWs.js b/infra/testing/webdriver/unregisterAllSWs.js index d157c5e69..d7063eaa1 100644 --- a/infra/testing/webdriver/unregisterAllSWs.js +++ b/infra/testing/webdriver/unregisterAllSWs.js @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - const {executeAsyncAndCatch} = require('./executeAsyncAndCatch'); /** diff --git a/infra/testing/webdriver/windowLoaded.js b/infra/testing/webdriver/windowLoaded.js index 03a74e76f..a79867e62 100644 --- a/infra/testing/webdriver/windowLoaded.js +++ b/infra/testing/webdriver/windowLoaded.js @@ -6,7 +6,6 @@ https://opensource.org/licenses/MIT. */ - const {executeAsyncAndCatch} = require('./executeAsyncAndCatch'); /** @@ -17,7 +16,9 @@ const windowLoaded = async () => { await executeAsyncAndCatch(async (cb) => { const loaded = () => { if (!window.Workbox) { - cb({error: `window.Workbox is undefined; location is ${location.href}`}); + cb({ + error: `window.Workbox is undefined; location is ${location.href}`, + }); } else { cb(); } diff --git a/infra/type-overrides.d.ts b/infra/type-overrides.d.ts index d6a529b5d..945720f6a 100644 --- a/infra/type-overrides.d.ts +++ b/infra/type-overrides.d.ts @@ -2,20 +2,35 @@ // https://github.com/microsoft/TSJS-lib-generator/pull/701 interface IDBIndex { - openCursor(range?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; - openKeyCursor(range?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; + openCursor( + range?: IDBValidKey | IDBKeyRange | null, + direction?: IDBCursorDirection, + ): IDBRequest; + openKeyCursor( + range?: IDBValidKey | IDBKeyRange | null, + direction?: IDBCursorDirection, + ): IDBRequest; } interface IDBObjectStore { - openCursor(range?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; - openKeyCursor(query?: IDBValidKey | IDBKeyRange | null, direction?: IDBCursorDirection): IDBRequest; + openCursor( + range?: IDBValidKey | IDBKeyRange | null, + direction?: IDBCursorDirection, + ): IDBRequest; + openKeyCursor( + query?: IDBValidKey | IDBKeyRange | null, + direction?: IDBCursorDirection, + ): IDBRequest; } // TODO(philipwalton): remove these once this PR makes its way to a release: // https://github.com/microsoft/TSJS-lib-generator/pull/740 interface CacheStorage { - match(request: RequestInfo, options?: MultiCacheQueryOptions): Promise; + match( + request: RequestInfo, + options?: MultiCacheQueryOptions, + ): Promise; } // TODO(philipwalton): remove these once this bug is fixed: diff --git a/infra/utils/log-helper.js b/infra/utils/log-helper.js index ede067d52..7fc1b1d0d 100644 --- a/infra/utils/log-helper.js +++ b/infra/utils/log-helper.js @@ -8,7 +8,7 @@ const chalk = require('chalk'); -const prefix = function() { +const prefix = function () { return chalk.inverse(`[Workbox]:`); }; diff --git a/javascript.eslintrc.js b/javascript.eslintrc.js index 8b6b4e4ea..3eb85eb7e 100644 --- a/javascript.eslintrc.js +++ b/javascript.eslintrc.js @@ -21,19 +21,23 @@ module.exports = { WorkboxSW: false, }, rules: { + 'indent': 0, 'jsdoc/check-types': 2, 'jsdoc/newline-after-description': 2, - 'max-len': [2, { - 'code': 80, - 'tabWidth': 2, - 'ignoreComments': true, - 'ignorePattern': '^\\s*import', - 'ignoreUrls': true, - }], + 'operator-linebreak': 0, + 'space-before-function-paren': 0, + 'max-len': [ + 2, + { + code: 80, + tabWidth: 2, + ignoreComments: true, + ignorePattern: '^\\s*import', + ignoreUrls: true, + }, + ], }, - plugins: [ - 'jsdoc', - ], + plugins: ['jsdoc'], settings: { jsdoc: { preferredTypes: { @@ -41,113 +45,104 @@ module.exports = { }, }, }, - overrides: [{ - files: ['test/**/*.{js,mjs}'], - env: { - mocha: true, - }, - globals: { - expectError: false, - waitUntil: false, - SW_NAMESPACES: false, - }, - rules: { - 'max-len': 0, - 'require-jsdoc': 0, - 'valid-jsdoc': 0, - 'no-invalid-this': 0, + overrides: [ + { + files: ['test/**/*.{js,mjs}'], + env: { + mocha: true, + }, + globals: { + expectError: false, + waitUntil: false, + SW_NAMESPACES: false, + }, + rules: { + 'max-len': 0, + 'require-jsdoc': 0, + 'valid-jsdoc': 0, + 'no-invalid-this': 0, + }, }, - }, { - files: [ - 'infra/testing/webdriver/executeAsyncAndCatch.js', - 'infra/testing/webdriver/runUnitTests.js', - 'infra/utils/log-helper.js', - 'packages/workbox-core/_private/logger.mjs', - 'packages/workbox-sw/_default.mjs', - 'packages/workbox-cli/src/lib/logger.js', - 'test/workbox-window/integration/test.js', - 'test/workbox-window/window/test-Workbox.mjs', - ], - rules: { - 'no-console': 0, + { + files: [ + 'infra/testing/webdriver/executeAsyncAndCatch.js', + 'infra/testing/webdriver/runUnitTests.js', + 'infra/utils/log-helper.js', + 'packages/workbox-core/_private/logger.mjs', + 'packages/workbox-sw/_default.mjs', + 'packages/workbox-cli/src/lib/logger.js', + 'test/workbox-window/integration/test.js', + 'test/workbox-window/window/test-Workbox.mjs', + ], + rules: { + 'no-console': 0, + }, }, - }, { - files: [ - 'infra/**/*.js', - ], - rules: { - 'max-len': 0, + { + files: ['infra/**/*.js'], + rules: { + 'max-len': 0, + }, }, - }, { - files: [ - 'gulp-tasks/**/*.js', - 'infra/**/*.js', - 'test/**/*.js', - ], - rules: { - 'camelcase': 0, - 'require-jsdoc': 0, - 'valid-jsdoc': 0, + { + files: ['gulp-tasks/**/*.js', 'infra/**/*.js', 'test/**/*.js'], + rules: { + 'camelcase': 0, + 'require-jsdoc': 0, + 'valid-jsdoc': 0, + }, }, - }, { - files: [ - 'infra/testing/**/*', - ], - env: { - 'mocha': true, + { + files: ['infra/testing/**/*'], + env: { + mocha: true, + }, }, - }, { - files: [ - 'test/*/static/**/*.js', - ], - rules: { - 'no-console': 0, - 'no-unused-vars': 0, - 'no-undef': 0, + { + files: ['test/*/static/**/*.js'], + rules: { + 'no-console': 0, + 'no-unused-vars': 0, + 'no-undef': 0, + }, }, - }, { - files: [ - 'packages/workbox-build/src/templates/**/*.js', - ], - rules: { - 'max-len': 0, + { + files: ['packages/workbox-build/src/templates/**/*.js'], + rules: { + 'max-len': 0, + }, }, - }, - { - files: [ - 'packages/workbox-sw/**/*', - ], - globals: { - 'workbox': false, + { + files: ['packages/workbox-sw/**/*'], + globals: { + workbox: false, + }, }, - }, { - files: [ - 'infra/testing/env-it.js', - ], - rules: { - 'no-invalid-this': 0, + { + files: ['infra/testing/env-it.js'], + rules: { + 'no-invalid-this': 0, + }, }, - }, { - files: [ - 'gulp-tasks/**/*.{mjs,js}', - 'infra/**/*.{mjs,js}', - 'packages/**/*.{mjs,js}', - 'test/**/*.{mjs,js}', - ], - plugins: [ - 'header', - ], - rules: { - 'header/header': [2, 'block', {pattern: 'Copyright \\d{4} Google LLC'}], + { + files: [ + 'gulp-tasks/**/*.{mjs,js}', + 'infra/**/*.{mjs,js}', + 'packages/**/*.{mjs,js}', + 'test/**/*.{mjs,js}', + ], + plugins: ['header'], + rules: { + 'header/header': [2, 'block', {pattern: 'Copyright \\d{4} Google LLC'}], + }, }, - }, { - files: [ - 'demos/**/*.js', - ], - rules: { - 'no-console': 0, + { + files: ['demos/**/*.js'], + rules: { + 'no-console': 0, + }, }, - }], + ], // eslint can't parse some of these files. ignorePatterns: ['**/wasm-project/**'], }; diff --git a/lerna.json b/lerna.json index 2e73644be..32d8ab2dd 100644 --- a/lerna.json +++ b/lerna.json @@ -1,7 +1,5 @@ { "lerna": "3.4.0", - "packages": [ - "packages/*" - ], + "packages": ["packages/*"], "version": "6.2.4" } diff --git a/package-lock.json b/package-lock.json index 502e46530..51500bb6e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6570,12 +6570,6 @@ "dot-prop": "^5.1.0" } }, - "compare-versions": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-3.6.0.tgz", - "integrity": "sha512-W6Af2Iw1z4CB7q4uU4hv646dW9GQuBM+YpC0UvUCWSD8w90SJjp+ujJuXaEMtAXBtSqGfMPuFOVn4/+FlaqfBA==", - "dev": true - }, "component-emitter": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/component-emitter/-/component-emitter-1.3.0.tgz", @@ -9231,15 +9225,6 @@ "path-exists": "^4.0.0" } }, - "find-versions": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/find-versions/-/find-versions-3.2.0.tgz", - "integrity": "sha512-P8WRou2S+oe222TOCHitLy8zj+SIsVJh52VP4lvXkaFVnOFFdoWv1H1Jjvel1aI6NCFOAaeAVm8qrI0odiLcww==", - "dev": true, - "requires": { - "semver-regex": "^2.0.0" - } - }, "findup-sync": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/findup-sync/-/findup-sync-3.0.0.tgz", @@ -9772,6 +9757,12 @@ "assert-plus": "^1.0.0" } }, + "git-format-staged": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/git-format-staged/-/git-format-staged-2.1.2.tgz", + "integrity": "sha512-ieP6iEyMJQ9xPKJGFSmK4HELcDdYwUO84dG4NBKdjaSTOdsZgrW9paLaEau2D4daPQjLwSsgwdqtYjqoVxz3Lw==", + "dev": true + }, "git-raw-commits": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/git-raw-commits/-/git-raw-commits-2.0.0.tgz", @@ -11117,43 +11108,10 @@ } }, "husky": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/husky/-/husky-4.3.0.tgz", - "integrity": "sha512-tTMeLCLqSBqnflBZnlVDhpaIMucSGaYyX6855jM4AguGeWCeSzNdb1mfyWduTZ3pe3SJVvVWGL0jO1iKZVPfTA==", - "dev": true, - "requires": { - "chalk": "^4.0.0", - "ci-info": "^2.0.0", - "compare-versions": "^3.6.0", - "cosmiconfig": "^7.0.0", - "find-versions": "^3.2.0", - "opencollective-postinstall": "^2.0.2", - "pkg-dir": "^4.2.0", - "please-upgrade-node": "^3.2.0", - "slash": "^3.0.0", - "which-pm-runs": "^1.0.0" - }, - "dependencies": { - "cosmiconfig": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.0.tgz", - "integrity": "sha512-pondGvTuVYDk++upghXJabWzL6Kxu6f26ljFw64Swq9v6sQPUL3EUlVDV56diOjpCayKihL6hVe8exIACU4XcA==", - "dev": true, - "requires": { - "@types/parse-json": "^4.0.0", - "import-fresh": "^3.2.1", - "parse-json": "^5.0.0", - "path-type": "^4.0.0", - "yaml": "^1.10.0" - } - }, - "slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true - } - } + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/husky/-/husky-7.0.2.tgz", + "integrity": "sha512-8yKEWNX4z2YsofXAMT7KvA1g8p+GxtB1ffV8XtpAEGuXNAbCV5wdNKH+qTpw8SM9fh4aMPDR+yQuKfgnreyZlg==", + "dev": true }, "iconv-lite": { "version": "0.4.24", @@ -14597,12 +14555,6 @@ "mimic-fn": "^2.1.0" } }, - "opencollective-postinstall": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.3.tgz", - "integrity": "sha512-8AV/sCtuzUeTo8gQK5qDZzARrulB3egtLzFgteqB2tcT4Mw7B8Kt7JcDHmltjz6FOAHsvTevk70gZEbhM4ZS9Q==", - "dev": true - }, "optionator": { "version": "0.9.1", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.1.tgz", @@ -15075,6 +15027,12 @@ "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", "dev": true }, + "prettier": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.3.2.tgz", + "integrity": "sha512-lnJzDfJ66zkMy58OL5/NY5zp70S7Nz6KqcKkXYzn2tMVrNxvbqaBpg7H3qHaLxCJ5lNMsGuM8+ohS7cZrthdLQ==", + "dev": true + }, "pretty-error": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.2.tgz", @@ -16289,12 +16247,6 @@ "sver-compat": "^1.5.0" } }, - "semver-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/semver-regex/-/semver-regex-2.0.0.tgz", - "integrity": "sha512-mUdIBBvdn0PLOeP3TEkMH7HHeUP3GjsXCwKarjv/kGmUFOYg1VqEemKhoQpWMu6X2I8kHeuVdGibLGkVK+/5Qw==", - "dev": true - }, "send": { "version": "0.17.1", "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", @@ -18935,12 +18887,6 @@ "integrity": "sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho=", "dev": true }, - "which-pm-runs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/which-pm-runs/-/which-pm-runs-1.0.0.tgz", - "integrity": "sha1-Zws6+8VS4LVd9rd4DKdGFfI60cs=", - "dev": true - }, "wide-align": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", diff --git a/package.json b/package.json index 8c3086a6e..3f759cec0 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,9 @@ "lint": "gulp lint", "test_server": "gulp test_server", "test_node": "gulp test_node", - "test_integration": "gulp test_integration" + "test_integration": "gulp test_integration", + "prepare": "husky install", + "format-staged": "git-format-staged -f 'prettier --ignore-unknown --stdin --stdin-filepath \"{}\"' ." }, "nyc": { "include": [ @@ -24,11 +26,6 @@ "packages/workbox-core/models/messages/messages.mjs" ] }, - "husky": { - "hooks": { - "pre-push": "gulp lint" - } - }, "version": "0.0.0", "description": "Top-level scripts and dependencies for the workbox monorepo. Not meant to be published to npm.", "private": true, @@ -86,13 +83,14 @@ "execa": "^4.0.3", "express": "^4.17.1", "fs-extra": "^9.0.1", + "git-format-staged": "^2.1.2", "glob": "^7.1.6", "globby": "^11.0.1", "gulp": "^4.0.2", "gzip-size": "^5.1.1", "html-webpack-plugin-v4": "npm:html-webpack-plugin@^4.5.0", "html-webpack-plugin-v5": "npm:html-webpack-plugin@^5.0.0-alpha.14", - "husky": "^4.2.5", + "husky": "^7.0.2", "idb": "^6.0.0", "jsdoc": "^3.6.5", "jsdoc-baseline": "^0.1.5", @@ -103,6 +101,7 @@ "module-alias": "^2.2.2", "nunjucks": "^3.2.2", "nyc": "^15.1.0", + "prettier": "^2.3.2", "proxyquire": "^2.1.3", "require-dir": "^1.2.0", "rollup": "^2.43.1", diff --git a/test/all/node/test-exports.js b/test/all/node/test-exports.js index 871c908da..dda8c1d70 100644 --- a/test/all/node/test-exports.js +++ b/test/all/node/test-exports.js @@ -13,8 +13,7 @@ const path = require('path'); const glob = require('glob'); const {getPackages} = require('../../../gulp-tasks/utils/get-packages'); - -describe(`[all] Window and SW packages`, function() { +describe(`[all] Window and SW packages`, function () { // Reading files can be slow. this.timeout(5 * 1000); @@ -23,9 +22,16 @@ describe(`[all] Window and SW packages`, function() { ...getPackages({type: 'window'}), ]; - it(`should have top a level module for every export in index.mjs (and vise-versa)`, async function() { + it(`should have top a level module for every export in index.mjs (and vise-versa)`, async function () { for (const pkg of windowAndSWPackages) { - const packagePath = path.join(__dirname, '..', '..', '..', 'packages', pkg.name); + const packagePath = path.join( + __dirname, + '..', + '..', + '..', + 'packages', + pkg.name, + ); // TODO(philipwalton): remove this once all packages are converted to // typescript or typescript adds `.mjs` support. @@ -42,7 +48,9 @@ describe(`[all] Window and SW packages`, function() { }); for (const node of indexAST.body) { if (node.type === 'ExportDefaultDeclaration') { - throw new Error(`'index.${ext}' files cannot contain default exports`); + throw new Error( + `'index.${ext}' files cannot contain default exports`, + ); } if (node.type === 'ExportNamedDeclaration') { for (const specifier of node.specifiers) { @@ -53,23 +61,34 @@ describe(`[all] Window and SW packages`, function() { // Inspect the package directory to get a list of top-level, public // module basenames. - const topLevelFiles = glob.sync(`*.${ext}`, { - ignore: ['index', 'types', '_types', '_version'].map((file) => `${file}.${ext}`), - cwd: packagePath, - }).map((file) => path.basename(file, `.${ext}`)); + const topLevelFiles = glob + .sync(`*.${ext}`, { + ignore: ['index', 'types', '_types', '_version'].map( + (file) => `${file}.${ext}`, + ), + cwd: packagePath, + }) + .map((file) => path.basename(file, `.${ext}`)); // Assert there's a 1-to-1 mapping between exports and top-level files. expect(namedExports.sort()).to.deep.equal(topLevelFiles.sort()); } }); - it(`should have top a level module for every export in _private.mjs (and vise-versa)`, async function() { + it(`should have top a level module for every export in _private.mjs (and vise-versa)`, async function () { for (const pkg of windowAndSWPackages) { // TODO(philipwalton): remove this once all packages are converted to // typescript or typescript adds `.mjs` support. const ext = 'types' in pkg ? 'js' : 'mjs'; - const packagePath = path.join(__dirname, '..', '..', '..', 'packages', pkg.name); + const packagePath = path.join( + __dirname, + '..', + '..', + '..', + 'packages', + pkg.name, + ); const privateFile = path.join(packagePath, `_private.${ext}`); // Only some packages have a `_private.mjs` module. @@ -87,11 +106,15 @@ describe(`[all] Window and SW packages`, function() { }); for (const node of indexAST.body) { if (node.type === 'ExportDefaultDeclaration') { - throw new Error(`'_private.${ext}' files cannot contain default exports`); + throw new Error( + `'_private.${ext}' files cannot contain default exports`, + ); } if (node.type === 'ExportNamedDeclaration') { if (node.specifiers.length === 0) { - throw new Error(`'_private.${ext}' files may only contain a single, named-export block`); + throw new Error( + `'_private.${ext}' files may only contain a single, named-export block`, + ); } for (const specifier of node.specifiers) { namedExports.push(specifier.exported.name); @@ -102,8 +125,9 @@ describe(`[all] Window and SW packages`, function() { // Inspect the package directory to get a list of top-level, public // module basenames. const privateDirectoryPath = path.join(packagePath, '_private'); - const topLevelFiles = glob.sync(`*.${ext}`, {cwd: privateDirectoryPath}) - .map((file) => path.basename(file, `.${ext}`)); + const topLevelFiles = glob + .sync(`*.${ext}`, {cwd: privateDirectoryPath}) + .map((file) => path.basename(file, `.${ext}`)); // Assert there's a 1-to-1 mapping between exports and top-level files. expect(namedExports.sort()).to.deep.equal(topLevelFiles.sort()); diff --git a/test/all/node/test-jsdocs.js b/test/all/node/test-jsdocs.js index af748174e..12fc158ca 100644 --- a/test/all/node/test-jsdocs.js +++ b/test/all/node/test-jsdocs.js @@ -13,8 +13,8 @@ const upath = require('path'); const {docs_build} = require('../../../gulp-tasks/docs.js'); -describe('[all] JSDocs', function() { - it('should run JSDocs and have no unexpected results', async function() { +describe('[all] JSDocs', function () { + it('should run JSDocs and have no unexpected results', async function () { // Windows is super unhappy with the JSDocs build pipeline. // With gulp.cmd in spawn, the query string used by the baseline template // causes issues. @@ -34,28 +34,37 @@ describe('[all] JSDocs', function() { }); // global.html is only added when the docs have stray global values. - expect(docs.includes('global.html'), - `'global.html' should not be present in ${docsPath}`).to.be.false; + expect( + docs.includes('global.html'), + `'global.html' should not be present in ${docsPath}`, + ).to.be.false; // On some occasions, module.exports can leak into JSDocs, and breaks // into the final template. - const indexAllHTML = await fse.readFile(upath.join(docsPath, 'index-all.html'), 'utf8'); - expect(indexAllHTML.includes('module.exports'), - `'module.exports' was found in index-all.html`).to.be.false; + const indexAllHTML = await fse.readFile( + upath.join(docsPath, 'index-all.html'), + 'utf8', + ); + expect( + indexAllHTML.includes( + 'module.exports', + ), + `'module.exports' was found in index-all.html`, + ).to.be.false; // We document this private method because we expect developers to // override it in their extending classes. - const privateMethodAllowlist = [ - '_handle', - ]; + const privateMethodAllowlist = ['_handle']; // string.matchAll() isn't supported before node v12... const regexp = //g; let match; while ((match = regexp.exec(indexAllHTML)) !== null) { const href = match[1]; - if (href.includes('#_') && - !privateMethodAllowlist.some((allow) => href.endsWith(allow))) { + if ( + href.includes('#_') && + !privateMethodAllowlist.some((allow) => href.endsWith(allow)) + ) { throw new Error(`Private method found in JSDocs: ${href}`); } } diff --git a/test/all/node/test-package.js b/test/all/node/test-package.js index 70ab7efa4..7a1e49189 100644 --- a/test/all/node/test-package.js +++ b/test/all/node/test-package.js @@ -17,8 +17,8 @@ const {getPackages} = require('../../../gulp-tasks/utils/get-packages'); const constants = require('../../../gulp-tasks/utils/constants'); const pkgPathToName = require('../../../gulp-tasks/utils/pkg-path-to-name'); -describe(`[all] Test package.json`, function() { - it(`should expose correct main, browser and module fields`, function() { +describe(`[all] Test package.json`, function () { + it(`should expose correct main, browser and module fields`, function () { const packageFiles = glob.sync('packages/**/package.json', { ignore: ['packages/*/node_modules/**/*'], cwd: upath.join(__dirname, '..', '..', '..'), @@ -28,19 +28,31 @@ describe(`[all] Test package.json`, function() { const pkg = require(packagePath); switch (pkg.workbox.packageType) { case 'sw': { - const propertiesToCheck = [ - 'main', - 'module', - ]; + const propertiesToCheck = ['main', 'module']; propertiesToCheck.forEach((propertyName) => { if (!pkg[propertyName]) { - throw new Error(`The package.json at '${upath.relative(process.cwd(), packagePath)}' isn't exposing a '${propertyName}' property`); + throw new Error( + `The package.json at '${upath.relative( + process.cwd(), + packagePath, + )}' isn't exposing a '${propertyName}' property`, + ); } - const fullPath = upath.join(upath.dirname(packagePath), pkg[propertyName]); + const fullPath = upath.join( + upath.dirname(packagePath), + pkg[propertyName], + ); if (!fs.existsSync(fullPath)) { - throw new Error(`${upath.relative(process.cwd(), packagePath)} has an invalid '${propertyName}' property: '${pkg[propertyName]}'`); + throw new Error( + `${upath.relative( + process.cwd(), + packagePath, + )} has an invalid '${propertyName}' property: '${ + pkg[propertyName] + }'`, + ); } }); break; @@ -55,12 +67,16 @@ describe(`[all] Test package.json`, function() { break; } default: - throw new Error(`Unknown package.json workbox.packageType: '${pkg.workbox.packageType}' in ${upath.relative(process.cwd(), packagePath)}`); + throw new Error( + `Unknown package.json workbox.packageType: '${ + pkg.workbox.packageType + }' in ${upath.relative(process.cwd(), packagePath)}`, + ); } }); }); - it(`should import _version.mjs in each .mjs file`, function() { + it(`should import _version.mjs in each .mjs file`, function () { // Find directories with package.json file const packageFiles = glob.sync('packages/*/package.json', { ignore: ['packages/*/node_modules/**/*'], @@ -97,13 +113,18 @@ describe(`[all] Test package.json`, function() { const fileContents = fs.readFileSync(filePath).toString(); const results = importRegex.exec(fileContents); if (!results) { - throw new Error(`Unable to find the workbox version in '${upath.relative(process.cwd(), filePath)}'`); + throw new Error( + `Unable to find the workbox version in '${upath.relative( + process.cwd(), + filePath, + )}'`, + ); } }); }); }); - it(`should contain the file version`, function() { + it(`should contain the file version`, function () { const versionRegex = /['|"]workbox:((?:[^:'"]*|:)*)['|"]/; // Find directories with package.json file @@ -121,18 +142,26 @@ describe(`[all] Test package.json`, function() { // Glob for all js and mjs files in the package const packageName = pkgPathToName(upath.dirname(packagePath)); - const packageFiles = glob.sync(`packages/${packageName}/${constants.PACKAGE_BUILD_DIRNAME}/**/*.{js,mjs}`, { - ignore: ['packages/*/node_modules/**/*'], - cwd: upath.join(__dirname, '..', '..', '..'), - absolute: true, - }); + const packageFiles = glob.sync( + `packages/${packageName}/${constants.PACKAGE_BUILD_DIRNAME}/**/*.{js,mjs}`, + { + ignore: ['packages/*/node_modules/**/*'], + cwd: upath.join(__dirname, '..', '..', '..'), + absolute: true, + }, + ); // Find the version in each file. packageFiles.forEach((filePath) => { const fileContents = fs.readFileSync(filePath).toString(); const results = versionRegex.exec(fileContents); if (!results) { - throw new Error(`Unable to find the workbox version in '${upath.relative(process.cwd(), filePath)}'`); + throw new Error( + `Unable to find the workbox version in '${upath.relative( + process.cwd(), + filePath, + )}'`, + ); } const metadata = results[1].split(':'); @@ -146,7 +175,7 @@ describe(`[all] Test package.json`, function() { }); }); - it(`should have correct details in _version.mjs`, function() { + it(`should have correct details in _version.mjs`, function () { const versionRegex = /['|"]workbox:((?:[^:'"]*|:)*)['|"]/; // Find directories with package.json file @@ -167,18 +196,26 @@ describe(`[all] Test package.json`, function() { const ext = 'types' in pkg ? 'js' : 'mjs'; const packageName = pkgPathToName(upath.dirname(packagePath)); - const versionFiles = glob.sync(`packages/${packageName}/_version.${ext}`, { - ignore: ['packages/*/node_modules/**/*'], - cwd: upath.join(__dirname, '..', '..', '..'), - absolute: true, - }); + const versionFiles = glob.sync( + `packages/${packageName}/_version.${ext}`, + { + ignore: ['packages/*/node_modules/**/*'], + cwd: upath.join(__dirname, '..', '..', '..'), + absolute: true, + }, + ); // Find the version in each file. versionFiles.forEach((filePath) => { const fileContents = fs.readFileSync(filePath).toString(); const results = versionRegex.exec(fileContents); if (!results) { - throw new Error(`Unable to find the workbox version in '${upath.relative(process.cwd(), filePath)}'`); + throw new Error( + `Unable to find the workbox version in '${upath.relative( + process.cwd(), + filePath, + )}'`, + ); } const metadata = results[1].split(':'); @@ -192,7 +229,7 @@ describe(`[all] Test package.json`, function() { }); }); - it(`should only use a namespace that matches its package name`, function() { + it(`should only use a namespace that matches its package name`, function () { const pkgs = getPackages({type: 'sw'}); for (const pkg of pkgs) { @@ -203,7 +240,10 @@ describe(`[all] Test package.json`, function() { const pkgNameSuffix = pkg.name.replace(/^workbox-/, ''); // Remvoe the `workbox.` prefix. - const pkgNamespaceSuffix = pkg.workbox.browserNamespace.replace(/^workbox\./, ''); + const pkgNamespaceSuffix = pkg.workbox.browserNamespace.replace( + /^workbox\./, + '', + ); if (camelCase(pkgNameSuffix) !== pkgNamespaceSuffix) { throw new Error(ol`Invalid browser namespace: diff --git a/test/all/node/test-prod-builds.js b/test/all/node/test-prod-builds.js index 0cabd784c..b1eb4abb3 100644 --- a/test/all/node/test-prod-builds.js +++ b/test/all/node/test-prod-builds.js @@ -13,29 +13,35 @@ const glob = require('glob'); const logHelper = require('../../../infra/utils/log-helper'); const path = require('path'); -describe(`[all] prod builds`, function() { - const buildFiles = glob.sync(`packages/*/${constants.PACKAGE_BUILD_DIRNAME}/*.prod.js`, { - ignore: ['packages/*/node_modules/**/*'], - cwd: path.join(__dirname, '..', '..', '..'), - absolute: true, - }); +describe(`[all] prod builds`, function () { + const buildFiles = glob.sync( + `packages/*/${constants.PACKAGE_BUILD_DIRNAME}/*.prod.js`, + { + ignore: ['packages/*/node_modules/**/*'], + cwd: path.join(__dirname, '..', '..', '..'), + absolute: true, + }, + ); - it(`should not have files with "console" or "%cworwbox"`, function() { + it(`should not have files with "console" or "%cworwbox"`, function () { const invalidFiles = []; buildFiles.forEach((filePath) => { const fileContents = fse.readFileSync(filePath).toString(); - if ((fileContents.indexOf(`console`) > -1 && - // See https://github.com/GoogleChrome/workbox/issues/2259 - !filePath.includes('workbox-precaching')) || - fileContents.indexOf(`%cworkbox`) > -1) { + if ( + (fileContents.indexOf(`console`) > -1 && + // See https://github.com/GoogleChrome/workbox/issues/2259 + !filePath.includes('workbox-precaching')) || + fileContents.indexOf(`%cworkbox`) > -1 + ) { invalidFiles.push(filePath); } }); if (invalidFiles.length > 0) { logHelper.error( - `Files with 'console' in them\n`, - JSON.stringify(invalidFiles, null, 2)); + `Files with 'console' in them\n`, + JSON.stringify(invalidFiles, null, 2), + ); throw new Error(oneLine` Found ${invalidFiles.length} files with "console" or "%cworkbox" in the final build. Please ensure all 'logger' calls are wrapped in a @@ -44,7 +50,7 @@ describe(`[all] prod builds`, function() { } }); - it(`should not have files with hasOwnProperty`, function() { + it(`should not have files with hasOwnProperty`, function () { const invalidFiles = []; buildFiles.forEach((filePath) => { const fileContents = fse.readFileSync(filePath).toString(); @@ -55,8 +61,9 @@ describe(`[all] prod builds`, function() { if (invalidFiles.length > 0) { logHelper.error( - `Files with 'hasOwnProperty('default')' in them\n`, - JSON.stringify(invalidFiles, null, 2)); + `Files with 'hasOwnProperty('default')' in them\n`, + JSON.stringify(invalidFiles, null, 2), + ); throw new Error(oneLine` Found ${invalidFiles.length} files with "hasOwnProperty('default')" in the final build. Please convert these to named exports to be friendly diff --git a/test/all/node/test-yarn-installation.js b/test/all/node/test-yarn-installation.js index ffbb166ce..d2d56ac62 100644 --- a/test/all/node/test-yarn-installation.js +++ b/test/all/node/test-yarn-installation.js @@ -18,13 +18,13 @@ const packagesToInstall = [ let temporaryDirectory; -describe('[all] Yarn Installation', function() { - before(async function() { +describe('[all] Yarn Installation', function () { + before(async function () { temporaryDirectory = await tempy.directory(); }); for (const packageToInstall of packagesToInstall) { - it(`should install ${packageToInstall} using yarn`, async function() { + it(`should install ${packageToInstall} using yarn`, async function () { this.timeout(5 * 60 * 1000); try { diff --git a/test/workbox-background-sync/integration/test-all.js b/test/workbox-background-sync/integration/test-all.js index 8be8d5345..ab7844351 100644 --- a/test/workbox-background-sync/integration/test-all.js +++ b/test/workbox-background-sync/integration/test-all.js @@ -11,44 +11,49 @@ const activateAndControlSW = require('../../../infra/testing/activate-and-contro const waitUntil = require('../../../infra/testing/wait-until'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-background-sync]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-background-sync]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-background-sync/sw/'); }); }); -describe(`[workbox-background-sync] Load and use Background Sync`, function() { +describe(`[workbox-background-sync] Load and use Background Sync`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-background-sync/static/basic-example/`; const swURL = `${testingURL}sw.js`; let requestCounter; - beforeEach(function() { + beforeEach(function () { requestCounter = server.startCountingRequests(); }); - afterEach(function() { + afterEach(function () { server.stopCountingRequests(requestCounter); }); - it(`should load a page with service worker`, async function() { + it(`should load a page with service worker`, async function () { // Load the page and wait for the first service worker to register and activate. await webdriver.get(testingURL); await activateAndControlSW(swURL); const url = `/test/workbox-background-sync/static/basic-example/example.txt`; const err = await webdriver.executeAsyncScript((url, cb) => { - return fetch(url).then(() => cb()).catch((err) => cb(err.message)); + return fetch(url) + .then(() => cb()) + .catch((err) => cb(err.message)); }, url); expect(err).to.not.exist; - await waitUntil(() => { - const count = requestCounter.getURLCount(url); - return count > 0; - }, 20, 500); + await waitUntil( + () => { + const count = requestCounter.getURLCount(url); + return count > 0; + }, + 20, + 500, + ); }); }); diff --git a/test/workbox-background-sync/static/basic-example/index.html b/test/workbox-background-sync/static/basic-example/index.html index 2fa6d40ea..7cc3d2ee9 100644 --- a/test/workbox-background-sync/static/basic-example/index.html +++ b/test/workbox-background-sync/static/basic-example/index.html @@ -1,7 +1,6 @@ - - +

    You need to manually register sw.js

    - + diff --git a/test/workbox-background-sync/static/basic-example/sw.js b/test/workbox-background-sync/static/basic-example/sw.js index bf1441149..f5c88cfec 100644 --- a/test/workbox-background-sync/static/basic-example/sw.js +++ b/test/workbox-background-sync/static/basic-example/sw.js @@ -15,7 +15,10 @@ const queue = new workbox.backgroundSync.Queue('myQueueName'); self.addEventListener('fetch', (event) => { const pathname = new URL(event.request.url).pathname; - if (pathname === '/test/workbox-background-sync/static/basic-example/example.txt') { + if ( + pathname === + '/test/workbox-background-sync/static/basic-example/example.txt' + ) { const queuePromise = (async () => { await queue.pushRequest({request: event.request}); // This is a horrible hack :( @@ -32,5 +35,9 @@ self.addEventListener('fetch', (event) => { } }); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-background-sync/sw/lib/test-QueueDb.mjs b/test/workbox-background-sync/sw/lib/test-QueueDb.mjs index 9760ff45c..59c31eb4b 100644 --- a/test/workbox-background-sync/sw/lib/test-QueueDb.mjs +++ b/test/workbox-background-sync/sw/lib/test-QueueDb.mjs @@ -383,7 +383,6 @@ describe(`QueueDb`, () => { }); }); - describe('deleteEntry', () => { it(`should delete an entry for the given ID`, async () => { const queueDb = new QueueDb(); diff --git a/test/workbox-background-sync/sw/lib/test-QueueStore.mjs b/test/workbox-background-sync/sw/lib/test-QueueStore.mjs index 33a62d66e..7ee7361a4 100644 --- a/test/workbox-background-sync/sw/lib/test-QueueStore.mjs +++ b/test/workbox-background-sync/sw/lib/test-QueueStore.mjs @@ -11,25 +11,25 @@ import {StorableRequest} from 'workbox-background-sync/lib/StorableRequest.mjs'; import {QueueDb} from 'workbox-background-sync/lib/QueueDb.mjs'; import {openDB} from 'idb'; -describe(`QueueStore`, function() { +describe(`QueueStore`, function () { let db = null; - beforeEach(async function() { + beforeEach(async function () { db = await openDB('workbox-background-sync', 3, { upgrade: QueueDb.prototype._upgradeDb, }); await db.clear('requests'); }); - describe(`constructor`, function() { - it(`should associate the queue name with a Queue instance`, function() { + describe(`constructor`, function () { + it(`should associate the queue name with a Queue instance`, function () { const queueStore = new QueueStore('foo'); expect(queueStore._queueName).to.equal('foo'); }); }); - describe(`pushEntry`, function() { - it(`should append an entry to IDB with the right queue name`, async function() { + describe(`pushEntry`, function () { + it(`should append an entry to IDB with the right queue name`, async function () { const queueStore1 = new QueueStore('a'); const queueStore2 = new QueueStore('b'); @@ -98,7 +98,7 @@ describe(`QueueStore`, function() { expect(entries[4].metadata).to.deep.equal({name: 'meta5'}); }); - it(`throws if not given an entry object`, function() { + it(`throws if not given an entry object`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -107,7 +107,7 @@ describe(`QueueStore`, function() { }, 'incorrect-type'); }); - it(`throws if not given an entry object with requestData`, function() { + it(`throws if not given an entry object with requestData`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -117,8 +117,8 @@ describe(`QueueStore`, function() { }); }); - describe(`unshiftEntry`, function() { - it(`should prepend an entry to IDB with the right queue name and ID`, async function() { + describe(`unshiftEntry`, function () { + it(`should prepend an entry to IDB with the right queue name and ID`, async function () { const queueStore1 = new QueueStore('a'); const queueStore2 = new QueueStore('b'); @@ -187,7 +187,7 @@ describe(`QueueStore`, function() { expect(entries[4].requestData.url).to.equal(`${location.origin}/one`); }); - it(`throws if not given an entry object`, function() { + it(`throws if not given an entry object`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -196,7 +196,7 @@ describe(`QueueStore`, function() { }, 'incorrect-type'); }); - it(`throws if not given an entry object with requestData`, function() { + it(`throws if not given an entry object with requestData`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -206,8 +206,8 @@ describe(`QueueStore`, function() { }); }); - describe(`shiftEntry`, function() { - it(`should remove and return the first entry in IDB with the matching queue name`, async function() { + describe(`shiftEntry`, function () { + it(`should remove and return the first entry in IDB with the matching queue name`, async function () { const queueStore1 = new QueueStore('a'); const queueStore2 = new QueueStore('b'); @@ -279,8 +279,8 @@ describe(`QueueStore`, function() { }); }); - describe(`popEntry`, function() { - it(`should remove and return the last entry in IDB with the matching queue name`, async function() { + describe(`popEntry`, function () { + it(`should remove and return the last entry in IDB with the matching queue name`, async function () { const queueStore1 = new QueueStore('a'); const queueStore2 = new QueueStore('b'); @@ -360,8 +360,8 @@ describe(`QueueStore`, function() { }); }); - describe(`getAll`, function() { - it(`should return all entries in IDB with the right queue name`, async function() { + describe(`getAll`, function () { + it(`should return all entries in IDB with the right queue name`, async function () { const queueStore1 = new QueueStore('a'); const queueStore2 = new QueueStore('b'); @@ -449,8 +449,8 @@ describe(`QueueStore`, function() { }); }); - describe(`delete`, function() { - it(`should delete an entry for the given ID`, async function() { + describe(`delete`, function () { + it(`should delete an entry for the given ID`, async function () { const queueStore = new QueueStore('a'); const sr1 = await StorableRequest.fromRequest(new Request('/one')); diff --git a/test/workbox-background-sync/sw/lib/test-StorableRequest.mjs b/test/workbox-background-sync/sw/lib/test-StorableRequest.mjs index 9c6f0f82b..f5c8ab0d1 100644 --- a/test/workbox-background-sync/sw/lib/test-StorableRequest.mjs +++ b/test/workbox-background-sync/sw/lib/test-StorableRequest.mjs @@ -8,20 +8,19 @@ import {StorableRequest} from 'workbox-background-sync/lib/StorableRequest.mjs'; - -describe(`StorableRequest`, function() { +describe(`StorableRequest`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe(`static fromRequest`, function() { - it(`should convert a Request to a StorableRequest instance`, async function() { + describe(`static fromRequest`, function () { + it(`should convert a Request to a StorableRequest instance`, async function () { const request = new Request('/foo', { method: 'POST', body: 'it worked!', @@ -33,7 +32,9 @@ describe(`StorableRequest`, function() { }); const storableRequest = await StorableRequest.fromRequest(request); - expect(storableRequest._requestData.url).to.equal(`${location.origin}/foo`); + expect(storableRequest._requestData.url).to.equal( + `${location.origin}/foo`, + ); expect(storableRequest._requestData.method).to.equal('POST'); expect(storableRequest._requestData.body).to.be.instanceOf(ArrayBuffer); expect(storableRequest._requestData.body.byteLength).to.equal(10); @@ -44,8 +45,8 @@ describe(`StorableRequest`, function() { }); }); - describe(`constructor`, function() { - it(`sets the passed properties on the instance`, function() { + describe(`constructor`, function () { + it(`sets the passed properties on the instance`, function () { const requestData = { url: '/foo', method: 'POST', @@ -61,7 +62,7 @@ describe(`StorableRequest`, function() { expect(storableRequest._requestData).to.deep.equal(requestData); }); - it(`handles navigation requests by converting them to same-origin`, async function() { + it(`handles navigation requests by converting them to same-origin`, async function () { const requestData = { url: '/api', method: 'POST', @@ -73,7 +74,7 @@ describe(`StorableRequest`, function() { expect(storableRequest._requestData.mode).to.equal('same-origin'); }); - it(`throws if not given a requestData object`, function() { + it(`throws if not given a requestData object`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -81,7 +82,7 @@ describe(`StorableRequest`, function() { }, 'incorrect-type'); }); - it(`throws if not given a URL in the requestData object`, function() { + it(`throws if not given a URL in the requestData object`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -90,18 +91,19 @@ describe(`StorableRequest`, function() { }); }); - describe(`toObject`, function() { - it(`converts the instance to a plain object`, async function() { + describe(`toObject`, function () { + it(`converts the instance to a plain object`, async function () { const storableRequest = await StorableRequest.fromRequest( - new Request('/foo', { - method: 'POST', - body: 'it worked!', - mode: 'cors', - headers: { - 'x-foo': 'bar', - 'x-qux': 'baz', - }, - })); + new Request('/foo', { + method: 'POST', + body: 'it worked!', + mode: 'cors', + headers: { + 'x-foo': 'bar', + 'x-qux': 'baz', + }, + }), + ); const requestData = storableRequest.toObject(); @@ -116,18 +118,19 @@ describe(`StorableRequest`, function() { }); }); - describe(`toRequest`, function() { - it(`converts the instance to a Request object`, async function() { + describe(`toRequest`, function () { + it(`converts the instance to a Request object`, async function () { const storableRequest = await StorableRequest.fromRequest( - new Request('/foo', { - method: 'POST', - body: 'it worked!', - mode: 'cors', - headers: { - 'x-foo': 'bar', - 'x-qux': 'baz', - }, - })); + new Request('/foo', { + method: 'POST', + body: 'it worked!', + mode: 'cors', + headers: { + 'x-foo': 'bar', + 'x-qux': 'baz', + }, + }), + ); const request = storableRequest.toRequest(); @@ -141,8 +144,8 @@ describe(`StorableRequest`, function() { }); }); - describe(`clone`, function() { - it(`creates a new instance with the same values`, async function() { + describe(`clone`, function () { + it(`creates a new instance with the same values`, async function () { const original = new StorableRequest({ url: '/foo', body: new Blob(['it worked!']), @@ -160,7 +163,8 @@ describe(`StorableRequest`, function() { // Ensure clone was not shallow. expect(original._requestData.body).to.not.equal(clone._requestData.body); expect(original._requestData.headers).to.not.equal( - clone._requestData.headers); + clone._requestData.headers, + ); }); }); }); diff --git a/test/workbox-background-sync/sw/test-BackgroundSyncPlugin.mjs b/test/workbox-background-sync/sw/test-BackgroundSyncPlugin.mjs index 77cd62121..af3c41409 100644 --- a/test/workbox-background-sync/sw/test-BackgroundSyncPlugin.mjs +++ b/test/workbox-background-sync/sw/test-BackgroundSyncPlugin.mjs @@ -14,10 +14,10 @@ function getUniqueQueueName() { return `queue-${count++}`; } -describe(`BackgroundSyncPlugin`, function() { +describe(`BackgroundSyncPlugin`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { // Don't actually register for a sync event in any test, as it could // make the tests non-deterministic. if ('sync' in registration) { @@ -25,12 +25,12 @@ describe(`BackgroundSyncPlugin`, function() { } }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`should implement fetchDidFail and add requests to the queue`, async function() { + describe(`constructor`, function () { + it(`should implement fetchDidFail and add requests to the queue`, async function () { const stub = sandbox.stub(Queue.prototype, 'pushRequest'); const queuePlugin = new BackgroundSyncPlugin(getUniqueQueueName()); diff --git a/test/workbox-background-sync/sw/test-Queue.mjs b/test/workbox-background-sync/sw/test-Queue.mjs index 56779c0db..11a6abcfa 100644 --- a/test/workbox-background-sync/sw/test-Queue.mjs +++ b/test/workbox-background-sync/sw/test-Queue.mjs @@ -15,11 +15,11 @@ import {dispatchAndWaitUntilDone} from '../../../infra/testing/helpers/extendabl const MINUTES = 60 * 1000; -describe(`Queue`, function() { +describe(`Queue`, function () { const sandbox = sinon.createSandbox(); let db = null; - beforeEach(async function() { + beforeEach(async function () { Queue._queueNames.clear(); db = await openDB('workbox-background-sync', 3, { upgrade: QueueDb.prototype._upgradeDb, @@ -43,15 +43,15 @@ describe(`Queue`, function() { sandbox.stub(Queue.prototype, 'replayRequests'); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - describe(`constructor`, function() { - it(`throws if two queues are created with the same name`, async function() { + describe(`constructor`, function () { + it(`throws if two queues are created with the same name`, async function () { expect(() => { new Queue('foo'); new Queue('bar'); @@ -66,7 +66,7 @@ describe(`Queue`, function() { }).not.to.throw(); }); - it(`adds a sync event listener (if supported) that runs the onSync function when a sync event is dispatched`, async function() { + it(`adds a sync event listener (if supported) that runs the onSync function when a sync event is dispatched`, async function () { if (!('sync' in registration)) this.skip(); const onSync = sandbox.spy(); @@ -77,20 +77,24 @@ describe(`Queue`, function() { expect(self.addEventListener.calledOnce).to.be.true; expect(self.addEventListener.calledWith('sync')).to.be.true; - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:foo', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:foo', + }), + ); // `onSync` should not be called because the tag won't match. - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:bar', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:bar', + }), + ); expect(onSync.callCount).to.equal(1); expect(onSync.firstCall.args[0].queue).to.equal(queue); }); - it(`defaults to calling replayRequests (if supported) when no onSync function is passed`, async function() { + it(`defaults to calling replayRequests (if supported) when no onSync function is passed`, async function () { if (!('sync' in registration)) this.skip(); const queue = new Queue('foo'); @@ -99,23 +103,28 @@ describe(`Queue`, function() { expect(self.addEventListener.calledOnce).to.be.true; expect(self.addEventListener.calledWith('sync')).to.be.true; - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:foo', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:foo', + }), + ); // `replayRequests` should not be called because the tag won't match. - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:bar', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:bar', + }), + ); // `replayRequsets` is stubbed in beforeEach, so we don't have to // re-stub in this test, and we can just assert it was called. expect(Queue.prototype.replayRequests.callCount).to.equal(1); - expect(Queue.prototype.replayRequests.firstCall.args[0].queue) - .to.equal(queue); + expect(Queue.prototype.replayRequests.firstCall.args[0].queue).to.equal( + queue, + ); }); - it(`registers a tag (if supported) if entries were added to the queue during a successful sync`, async function() { + it(`registers a tag (if supported) if entries were added to the queue during a successful sync`, async function () { if (!('sync' in registration)) this.skip(); const onSync = sandbox.stub().callsFake(async ({queue}) => { @@ -133,14 +142,16 @@ describe(`Queue`, function() { const queue = new Queue('foo', {onSync}); sandbox.spy(queue, 'registerSync'); - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:foo', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:foo', + }), + ); expect(queue.registerSync.callCount).to.equal(1); }); - it(`doesn't re-register after a sync event fails`, async function() { + it(`doesn't re-register after a sync event fails`, async function () { if (!('sync' in registration)) this.skip(); const onSync = async ({queue}) => { @@ -153,14 +164,16 @@ describe(`Queue`, function() { const queue = new Queue('foo', {onSync}); sandbox.spy(queue, 'registerSync'); - await dispatchAndWaitUntilDone(new SyncEvent('sync', { - tag: 'workbox-background-sync:foo', - })); + await dispatchAndWaitUntilDone( + new SyncEvent('sync', { + tag: 'workbox-background-sync:foo', + }), + ); expect(queue.registerSync.callCount).to.equal(0); }); - it(`re-registers a tag after a sync event fails if event.lastChance is true`, async function() { + it(`re-registers a tag after a sync event fails if event.lastChance is true`, async function () { if (!('sync' in registration)) this.skip(); const onSync = async ({queue}) => { @@ -182,7 +195,7 @@ describe(`Queue`, function() { expect(queue.registerSync.callCount).to.equal(1); }); - it(`tries to run the sync logic on instantiation iff the browser doesn't support Background Sync`, async function() { + it(`tries to run the sync logic on instantiation iff the browser doesn't support Background Sync`, async function () { const onSync = sandbox.spy(); new Queue('foo', {onSync}); @@ -194,8 +207,8 @@ describe(`Queue`, function() { }); }); - describe(`pushRequest`, function() { - it(`should add the request to the end QueueStore instance`, async function() { + describe(`pushRequest`, function () { + it(`should add the request to the end QueueStore instance`, async function () { sandbox.spy(QueueStore.prototype, 'pushEntry'); const queue = new Queue('a'); @@ -217,14 +230,16 @@ describe(`Queue`, function() { const args = QueueStore.prototype.pushEntry.firstCall.args; expect(args[0].requestData.url).to.equal(requestURL); expect(args[0].requestData.method).to.equal(requestInit.method); - expect(args[0].requestData.headers['x-foo']).to.equal(requestInit.headers['x-foo']); + expect(args[0].requestData.headers['x-foo']).to.equal( + requestInit.headers['x-foo'], + ); expect(args[0].requestData.mode).to.deep.equal(requestInit.mode); expect(args[0].requestData.body).to.be.instanceOf(ArrayBuffer); expect(args[0].timestamp).to.equal(timestamp); expect(args[0].metadata).to.deep.equal(metadata); }); - it(`should not require metadata`, async function() { + it(`should not require metadata`, async function () { sandbox.spy(QueueStore.prototype, 'pushEntry'); const queue = new Queue('a'); @@ -238,7 +253,7 @@ describe(`Queue`, function() { expect(args[0].metadata).to.be.undefined; }); - it(`should use the current time as the timestamp when not specified`, async function() { + it(`should use the current time as the timestamp when not specified`, async function () { sandbox.spy(QueueStore.prototype, 'pushEntry'); sandbox.useFakeTimers({ @@ -257,7 +272,7 @@ describe(`Queue`, function() { expect(args[0].timestamp).to.equal(1234); }); - it(`should register to receive sync events for a unique tag`, async function() { + it(`should register to receive sync events for a unique tag`, async function () { if (!('sync' in registration)) this.skip(); const queue = new Queue('foo'); @@ -266,13 +281,16 @@ describe(`Queue`, function() { // self.registration.sync.register is stubbed in `beforeEach()`. expect(self.registration.sync.register.calledOnce).to.be.true; - expect(self.registration.sync.register.calledWith( - 'workbox-background-sync:foo')).to.be.true; + expect( + self.registration.sync.register.calledWith( + 'workbox-background-sync:foo', + ), + ).to.be.true; }); }); - describe(`unshiftRequest`, function() { - it(`should add the request to the beginning of the QueueStore`, async function() { + describe(`unshiftRequest`, function () { + it(`should add the request to the beginning of the QueueStore`, async function () { sandbox.spy(QueueStore.prototype, 'unshiftEntry'); const queue = new Queue('a'); @@ -294,14 +312,16 @@ describe(`Queue`, function() { const args = QueueStore.prototype.unshiftEntry.firstCall.args; expect(args[0].requestData.url).to.equal(requestURL); expect(args[0].requestData.method).to.equal(requestInit.method); - expect(args[0].requestData.headers['x-foo']).to.equal(requestInit.headers['x-foo']); + expect(args[0].requestData.headers['x-foo']).to.equal( + requestInit.headers['x-foo'], + ); expect(args[0].requestData.mode).to.deep.equal(requestInit.mode); expect(args[0].requestData.body).to.be.instanceOf(ArrayBuffer); expect(args[0].timestamp).to.equal(timestamp); expect(args[0].metadata).to.deep.equal(metadata); }); - it(`should not require metadata`, async function() { + it(`should not require metadata`, async function () { sandbox.spy(QueueStore.prototype, 'unshiftEntry'); const queue = new Queue('a'); @@ -315,7 +335,7 @@ describe(`Queue`, function() { expect(args[0].metadata).to.be.undefined; }); - it(`should use the current time as the timestamp when not specified`, async function() { + it(`should use the current time as the timestamp when not specified`, async function () { sandbox.spy(QueueStore.prototype, 'unshiftEntry'); const queue = new Queue('a'); @@ -332,7 +352,7 @@ describe(`Queue`, function() { expect(args[0].timestamp <= endTime).to.be.ok; }); - it(`should register to receive sync events for a unique tag`, async function() { + it(`should register to receive sync events for a unique tag`, async function () { if (!('sync' in registration)) this.skip(); const queue = new Queue('foo'); @@ -343,13 +363,16 @@ describe(`Queue`, function() { // self.registration.sync.register is stubbed in `beforeEach()`. expect(self.registration.sync.register.calledOnce).to.be.true; - expect(self.registration.sync.register.calledWith( - 'workbox-background-sync:foo')).to.be.true; + expect( + self.registration.sync.register.calledWith( + 'workbox-background-sync:foo', + ), + ).to.be.true; }); }); - describe(`shiftRequest`, function() { - it(`gets and removes the first request in the QueueStore instance`, async function() { + describe(`shiftRequest`, function () { + it(`gets and removes the first request in the QueueStore instance`, async function () { sandbox.spy(QueueStore.prototype, 'shiftEntry'); const queue = new Queue('a'); @@ -374,10 +397,11 @@ describe(`Queue`, function() { expect(request.mode).to.deep.equal(requestInit.mode); expect(await request.text()).to.equal(requestInit.body); expect(request.headers.get('x-foo')).to.equal( - requestInit.headers['x-foo']); + requestInit.headers['x-foo'], + ); }); - it(`returns the timestamp and any passed metadata along with the request`, async function() { + it(`returns the timestamp and any passed metadata along with the request`, async function () { const queue = new Queue('a'); await queue.pushRequest({ @@ -391,7 +415,7 @@ describe(`Queue`, function() { expect(metadata).to.deep.equal({meta: 'data'}); }); - it(`does not return requests that have expired`, async function() { + it(`does not return requests that have expired`, async function () { const queue = new Queue('a'); await queue.pushRequest({ @@ -419,8 +443,8 @@ describe(`Queue`, function() { }); }); - describe(`popRequest`, function() { - it(`gets and removes the last request in the QueueStore instance`, async function() { + describe(`popRequest`, function () { + it(`gets and removes the last request in the QueueStore instance`, async function () { sandbox.spy(QueueStore.prototype, 'popEntry'); const queue = new Queue('a'); @@ -448,10 +472,11 @@ describe(`Queue`, function() { expect(request.mode).to.deep.equal(requestInit.mode); expect(await request.text()).to.equal(requestInit.body); expect(request.headers.get('x-foo')).to.equal( - requestInit.headers['x-foo']); + requestInit.headers['x-foo'], + ); }); - it(`returns the timestamp and any passed metadata along with the request`, async function() { + it(`returns the timestamp and any passed metadata along with the request`, async function () { const queue = new Queue('a'); await queue.pushRequest({ @@ -465,7 +490,7 @@ describe(`Queue`, function() { expect(metadata).to.deep.equal({meta: 'data'}); }); - it(`does not return requests that have expired`, async function() { + it(`does not return requests that have expired`, async function () { const queue = new Queue('a'); await queue.pushRequest({ @@ -493,13 +518,13 @@ describe(`Queue`, function() { }); }); - describe(`replayRequests`, function() { - beforeEach(function() { + describe(`replayRequests`, function () { + beforeEach(function () { // Unstub replayRequests for all tests in this group. Queue.prototype.replayRequests.restore(); }); - it(`should try to re-fetch all requests in the queue`, async function() { + it(`should try to re-fetch all requests in the queue`, async function () { sandbox.stub(self, 'fetch'); const queue1 = new Queue('foo'); @@ -527,31 +552,51 @@ describe(`Queue`, function() { expect(self.fetch.callCount).to.equal(3); - expect(self.fetch.getCall(0).calledWith(sinon.match({ - url: `${location.origin}/one`, - }))).to.be.true; - - expect(self.fetch.getCall(1).calledWith(sinon.match({ - url: `${location.origin}/three`, - }))).to.be.true; - - expect(self.fetch.getCall(2).calledWith(sinon.match({ - url: `${location.origin}/five`, - }))).to.be.true; + expect( + self.fetch.getCall(0).calledWith( + sinon.match({ + url: `${location.origin}/one`, + }), + ), + ).to.be.true; + + expect( + self.fetch.getCall(1).calledWith( + sinon.match({ + url: `${location.origin}/three`, + }), + ), + ).to.be.true; + + expect( + self.fetch.getCall(2).calledWith( + sinon.match({ + url: `${location.origin}/five`, + }), + ), + ).to.be.true; await queue2.replayRequests(); expect(self.fetch.callCount).to.equal(5); - expect(self.fetch.getCall(3).calledWith(sinon.match({ - url: `${location.origin}/two`, - }))).to.be.true; + expect( + self.fetch.getCall(3).calledWith( + sinon.match({ + url: `${location.origin}/two`, + }), + ), + ).to.be.true; - expect(self.fetch.getCall(4).calledWith(sinon.match({ - url: `${location.origin}/four`, - }))).to.be.true; + expect( + self.fetch.getCall(4).calledWith( + sinon.match({ + url: `${location.origin}/four`, + }), + ), + ).to.be.true; }); - it(`should remove requests after a successful retry`, async function() { + it(`should remove requests after a successful retry`, async function () { sandbox.spy(self, 'fetch'); const queue1 = new Queue('foo'); @@ -584,7 +629,7 @@ describe(`Queue`, function() { expect(entries[1].requestData.url).to.equal(`${location.origin}/four`); }); - it(`should ignore (and remove) requests if maxRetentionTime has passed`, async function() { + it(`should ignore (and remove) requests if maxRetentionTime has passed`, async function () { sandbox.spy(self, 'fetch'); const clock = sandbox.useFakeTimers({ now: Date.now(), @@ -605,27 +650,34 @@ describe(`Queue`, function() { clock.tick(1 * MINUTES + 1); // One minute and 1ms. await queue.pushRequest({ - request: new Request('/three')}); + request: new Request('/three'), + }); await queue.replayRequests(); expect(self.fetch.calledOnce).to.be.true; - expect(self.fetch.calledWith(sinon.match({ - url: `${location.origin}/three`, - }))).to.be.true; + expect( + self.fetch.calledWith( + sinon.match({ + url: `${location.origin}/three`, + }), + ), + ).to.be.true; const entries = await db.getAll('requests'); // Assert that the two requests not replayed were deleted. expect(entries.length).to.equal(0); }); - it(`should stop replaying if a request fails`, async function() { - sandbox.stub(self, 'fetch') - .onCall(3).callsFake(async (request) => { - // Use the body to ensure everything is cloned beforehand. - await request.text(); - throw new Error('network error'); - }) - .callThrough(); + it(`should stop replaying if a request fails`, async function () { + sandbox + .stub(self, 'fetch') + .onCall(3) + .callsFake(async (request) => { + // Use the body to ensure everything is cloned beforehand. + await request.text(); + throw new Error('network error'); + }) + .callThrough(); const queue = new Queue('foo'); @@ -655,14 +707,16 @@ describe(`Queue`, function() { expect(entries[1].requestData.url).to.equal(`${location.origin}/five`); }); - it(`should throw WorkboxError if re-fetching fails`, async function() { - sandbox.stub(self, 'fetch') - .onCall(1).callsFake(async (request) => { - // Use the body to ensure everything is cloned beforehand. - await request.text(); - throw new Error('network error'); - }) - .callThrough(); + it(`should throw WorkboxError if re-fetching fails`, async function () { + sandbox + .stub(self, 'fetch') + .onCall(1) + .callsFake(async (request) => { + // Use the body to ensure everything is cloned beforehand. + await request.text(); + throw new Error('network error'); + }) + .callThrough(); const queue = new Queue('foo'); @@ -681,13 +735,13 @@ describe(`Queue`, function() { }); }); - describe(`registerSync()`, function() { - it(`should succeed regardless of browser support for sync`, async function() { + describe(`registerSync()`, function () { + it(`should succeed regardless of browser support for sync`, async function () { const queue = new Queue('a'); await queue.registerSync(); }); - it(`should handle thrown errors in sync registration`, async function() { + it(`should handle thrown errors in sync registration`, async function () { if (!('sync' in registration)) this.skip(); registration.sync.register.restore(); @@ -701,8 +755,8 @@ describe(`Queue`, function() { }); }); - describe(`getAll()`, function() { - it(`returns all requests in the QueueStore instance`, async function() { + describe(`getAll()`, function () { + it(`returns all requests in the QueueStore instance`, async function () { const queue = new Queue('a'); const request1 = new Request('/one', {method: 'POST', body: '...'}); @@ -729,7 +783,7 @@ describe(`Queue`, function() { expect(await db.getAll('requests')).to.have.lengthOf(3); }); - it(`doesn't return expired entries (and it deletes them)`, async function() { + it(`doesn't return expired entries (and it deletes them)`, async function () { const queue = new Queue('a'); const request1 = new Request('/one', {method: 'POST', body: '...'}); diff --git a/test/workbox-broadcast-update/integration/test-all.js b/test/workbox-broadcast-update/integration/test-all.js index 50f3ff2d8..648c96a06 100644 --- a/test/workbox-broadcast-update/integration/test-all.js +++ b/test/workbox-broadcast-update/integration/test-all.js @@ -9,7 +9,9 @@ const expect = require('chai').expect; const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); -const {IframeManager} = require('../../../infra/testing/webdriver/IframeManager'); +const { + IframeManager, +} = require('../../../infra/testing/webdriver/IframeManager'); const activateAndControlSW = require('../../../infra/testing/activate-and-control'); const cleanSWEnv = require('../../../infra/testing/clean-sw'); const templateData = require('../../../infra/testing/server/template-data'); @@ -17,34 +19,38 @@ const templateData = require('../../../infra/testing/server/template-data'); // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-broadcast-update]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-broadcast-update]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-broadcast-update/sw/'); }); }); -describe(`[workbox-broadcast-update] Plugin`, function() { +describe(`[workbox-broadcast-update] Plugin`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-broadcast-update/static/`; const swURL = `${testingURL}sw.js`; const apiURL = `${testServerAddress}/__WORKBOX/uniqueETag`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, testingURL); await activateAndControlSW(swURL); }); - it(`should broadcast a message when there's a cache update to a regular request`, async function() { + it(`should broadcast a message when there's a cache update to a regular request`, async function () { // Fetch `apiURL`, which should put it in the cache (but not trigger an update) const err1 = await webdriver.executeAsyncScript((apiURL, cb) => { - fetch(apiURL).then(() => cb()).catch((err) => cb(err.message)); + fetch(apiURL) + .then(() => cb()) + .catch((err) => cb(err.message)); }, apiURL); expect(err1).to.not.exist; // Fetch `apiURL` again, which should trigger an update message. const err2 = await webdriver.executeAsyncScript((apiURL, cb) => { - fetch(apiURL).then(() => cb()).catch((err) => cb(err.message)); + fetch(apiURL) + .then(() => cb()) + .catch((err) => cb(err.message)); }, apiURL); expect(err2).to.not.exist; @@ -69,7 +75,7 @@ describe(`[workbox-broadcast-update] Plugin`, function() { }); }); - it(`should broadcast a message when there's a cache update to a navigation request`, async function() { + it(`should broadcast a message when there's a cache update to a navigation request`, async function () { templateData.assign({ title: 'Broadcast Cache Update Test', body: 'Second test, initial body.', @@ -121,7 +127,7 @@ describe(`[workbox-broadcast-update] Plugin`, function() { }); }); - it(`should broadcast a message to all open window clients by default`, async function() { + it(`should broadcast a message to all open window clients by default`, async function () { const iframeManager = new IframeManager(webdriver); templateData.assign({ @@ -162,38 +168,46 @@ describe(`[workbox-broadcast-update] Plugin`, function() { return window.__messages; }); - expect(tab1Messages).to.eql([{ - type: 'CACHE_UPDATED', - meta: 'workbox-broadcast-update', - payload: { - cacheName: 'bcu-integration-test', - updatedURL: dynamicPageURL, + expect(tab1Messages).to.eql([ + { + type: 'CACHE_UPDATED', + meta: 'workbox-broadcast-update', + payload: { + cacheName: 'bcu-integration-test', + updatedURL: dynamicPageURL, + }, }, - }]); + ]); }); - it(`should only broadcast a message to the client that made the request when notifyAllClients is false`, async function() { + it(`should only broadcast a message to the client that made the request when notifyAllClients is false`, async function () { const url = `${apiURL}?notifyAllClientsTest`; const iframeManager = new IframeManager(webdriver); await webdriver.get(testingURL); await webdriver.executeAsyncScript((url, cb) => { - fetch(url).then(() => cb()).catch((err) => cb(err.message)); + fetch(url) + .then(() => cb()) + .catch((err) => cb(err.message)); }, url); const iframeClient = await iframeManager.createIframeClient(testingURL); await iframeClient.executeAsyncScript(`fetch(${JSON.stringify(url)})`); await iframeClient.wait('window.__messages.length > 0'); - const populatedMessages = await iframeClient.executeAsyncScript('window.__messages'); - expect(populatedMessages).to.eql([{ - type: 'CACHE_UPDATED', - meta: 'workbox-broadcast-update', - payload: { - cacheName: 'bcu-integration-test', - updatedURL: url, + const populatedMessages = await iframeClient.executeAsyncScript( + 'window.__messages', + ); + expect(populatedMessages).to.eql([ + { + type: 'CACHE_UPDATED', + meta: 'workbox-broadcast-update', + payload: { + cacheName: 'bcu-integration-test', + updatedURL: url, + }, }, - }]); + ]); const unpopulatedMessages = await webdriver.executeScript(() => { return window.__messages; diff --git a/test/workbox-broadcast-update/static/index.html b/test/workbox-broadcast-update/static/index.html index 8a9c47e94..1570f48a0 100644 --- a/test/workbox-broadcast-update/static/index.html +++ b/test/workbox-broadcast-update/static/index.html @@ -1,6 +1,5 @@ - - +

    You need to manually register sw.js

    - + diff --git a/test/workbox-broadcast-update/static/sw.js b/test/workbox-broadcast-update/static/sw.js index fba31e44d..3d20cdf43 100644 --- a/test/workbox-broadcast-update/static/sw.js +++ b/test/workbox-broadcast-update/static/sw.js @@ -14,35 +14,31 @@ importScripts('/__WORKBOX/buildFile/workbox-strategies'); const cacheName = 'bcu-integration-test'; workbox.routing.registerRoute( - ({url}) => url.searchParams.has('notifyAllClientsTest'), - new workbox.strategies.NetworkFirst({ - cacheName, - plugins: [ - new workbox.broadcastUpdate.BroadcastUpdatePlugin({ - notifyAllClients: false, - }), - ], - }), + ({url}) => url.searchParams.has('notifyAllClientsTest'), + new workbox.strategies.NetworkFirst({ + cacheName, + plugins: [ + new workbox.broadcastUpdate.BroadcastUpdatePlugin({ + notifyAllClients: false, + }), + ], + }), ); workbox.routing.registerRoute( - new RegExp('/__WORKBOX/uniqueETag$'), - new workbox.strategies.StaleWhileRevalidate({ - cacheName, - plugins: [ - new workbox.broadcastUpdate.BroadcastUpdatePlugin(), - ], - }), + new RegExp('/__WORKBOX/uniqueETag$'), + new workbox.strategies.StaleWhileRevalidate({ + cacheName, + plugins: [new workbox.broadcastUpdate.BroadcastUpdatePlugin()], + }), ); workbox.routing.registerRoute( - ({request}) => request.mode === 'navigate', - new workbox.strategies.StaleWhileRevalidate({ - cacheName, - plugins: [ - new workbox.broadcastUpdate.BroadcastUpdatePlugin(), - ], - }), + ({request}) => request.mode === 'navigate', + new workbox.strategies.StaleWhileRevalidate({ + cacheName, + plugins: [new workbox.broadcastUpdate.BroadcastUpdatePlugin()], + }), ); self.addEventListener('install', () => self.skipWaiting()); diff --git a/test/workbox-broadcast-update/sw/test-BroadcastCacheUpdate.mjs b/test/workbox-broadcast-update/sw/test-BroadcastCacheUpdate.mjs index ad2b837fe..ff8d73b92 100644 --- a/test/workbox-broadcast-update/sw/test-BroadcastCacheUpdate.mjs +++ b/test/workbox-broadcast-update/sw/test-BroadcastCacheUpdate.mjs @@ -7,56 +7,57 @@ */ import {BroadcastCacheUpdate} from 'workbox-broadcast-update/BroadcastCacheUpdate.mjs'; -import {CACHE_UPDATED_MESSAGE_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK} from 'workbox-broadcast-update/utils/constants.mjs'; +import { + CACHE_UPDATED_MESSAGE_META, + CACHE_UPDATED_MESSAGE_TYPE, + DEFAULT_HEADERS_TO_CHECK, +} from 'workbox-broadcast-update/utils/constants.mjs'; - -describe(`BroadcastCacheUpdate`, function() { +describe(`BroadcastCacheUpdate`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - describe(`constructor()`, function() { - it(`should use the passed headersToCheck`, function() { - const headersToCheck = [ - 'hello-1', - 'hello-2', - ]; + describe(`constructor()`, function () { + it(`should use the passed headersToCheck`, function () { + const headersToCheck = ['hello-1', 'hello-2']; const bcu = new BroadcastCacheUpdate({headersToCheck}); expect(bcu._headersToCheck).to.equal(headersToCheck); }); - it(`should use the default headersToCheck when not passed`, function() { + it(`should use the default headersToCheck when not passed`, function () { const bcu = new BroadcastCacheUpdate(); expect(bcu._headersToCheck).to.deep.equal(DEFAULT_HEADERS_TO_CHECK); }); - it(`should use the passed generatePayload`, function() { + it(`should use the passed generatePayload`, function () { const generatePayload = () => {}; const bcu = new BroadcastCacheUpdate({generatePayload}); expect(bcu._generatePayload).to.equal(generatePayload); }); - it(`should use the default generatePayload when not passed`, function() { + it(`should use the default generatePayload when not passed`, function () { const bcu = new BroadcastCacheUpdate(); expect(bcu._generatePayload).to.be.a('function'); }); }); - describe(`notifyIfUpdated()`, function() { - it(`should broadcast update if responses are different`, async function() { + describe(`notifyIfUpdated()`, function () { + it(`should broadcast update if responses are different`, async function () { const bcu = new BroadcastCacheUpdate(); const pm1Spy = sandbox.spy(); const pm2Spy = sandbox.spy(); - sandbox.stub(self.clients, 'matchAll') - .withArgs(sinon.match.has('type', 'window')) - .resolves([{postMessage: pm1Spy}, {postMessage: pm2Spy}]); + sandbox + .stub(self.clients, 'matchAll') + .withArgs(sinon.match.has('type', 'window')) + .resolves([{postMessage: pm1Spy}, {postMessage: pm2Spy}]); await bcu.notifyIfUpdated({ oldResponse: new Response('', { @@ -84,14 +85,15 @@ describe(`BroadcastCacheUpdate`, function() { expect(pm2Spy.args[0][0]).to.deep.equal(expectData); }); - it(`should not broadcast update if responses are the same`, async function() { + it(`should not broadcast update if responses are the same`, async function () { const bcu = new BroadcastCacheUpdate(); const pm1Spy = sandbox.spy(); const pm2Spy = sandbox.spy(); - sandbox.stub(self.clients, 'matchAll') - .withArgs(sinon.match.has('type', 'window')) - .resolves([{postMessage: pm1Spy}, {postMessage: pm2Spy}]); + sandbox + .stub(self.clients, 'matchAll') + .withArgs(sinon.match.has('type', 'window')) + .resolves([{postMessage: pm1Spy}, {postMessage: pm2Spy}]); await bcu.notifyIfUpdated({ oldResponse: new Response('', { @@ -108,7 +110,7 @@ describe(`BroadcastCacheUpdate`, function() { expect(pm2Spy.callCount).to.equal(0); }); - it(`should throw when called and cacheName is missing`, function() { + it(`should throw when called and cacheName is missing`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -120,7 +122,7 @@ describe(`BroadcastCacheUpdate`, function() { }, 'incorrect-type'); }); - it(`should throw when called and newResponse is missing`, function() { + it(`should throw when called and newResponse is missing`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { @@ -132,7 +134,7 @@ describe(`BroadcastCacheUpdate`, function() { }, 'incorrect-class'); }); - it(`should throw when called and request is missing`, function() { + it(`should throw when called and request is missing`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(async () => { diff --git a/test/workbox-broadcast-update/sw/test-BroadcastUpdatePlugin.mjs b/test/workbox-broadcast-update/sw/test-BroadcastUpdatePlugin.mjs index 8e7a00b8b..60e3931cd 100644 --- a/test/workbox-broadcast-update/sw/test-BroadcastUpdatePlugin.mjs +++ b/test/workbox-broadcast-update/sw/test-BroadcastUpdatePlugin.mjs @@ -8,20 +8,19 @@ import {BroadcastUpdatePlugin} from '../../../packages/workbox-broadcast-update/BroadcastUpdatePlugin.mjs'; - -describe(`BroadcastUpdatePlugin`, function() { +describe(`BroadcastUpdatePlugin`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - describe(`cacheDidUpdate`, function() { - it(`should call notifyIfUpdated and pass all options`, async function() { + describe(`cacheDidUpdate`, function () { + it(`should call notifyIfUpdated and pass all options`, async function () { const bcuPlugin = new BroadcastUpdatePlugin(); sandbox.stub(bcuPlugin._broadcastUpdate, 'notifyIfUpdated').resolves(); @@ -29,7 +28,9 @@ describe(`BroadcastUpdatePlugin`, function() { await bcuPlugin.cacheDidUpdate(opts); expect(bcuPlugin._broadcastUpdate.notifyIfUpdated.callCount).to.equal(1); - expect(bcuPlugin._broadcastUpdate.notifyIfUpdated.args[0][0]).to.equal(opts); + expect(bcuPlugin._broadcastUpdate.notifyIfUpdated.args[0][0]).to.equal( + opts, + ); }); }); }); diff --git a/test/workbox-broadcast-update/sw/test-responsesAreSame.mjs b/test/workbox-broadcast-update/sw/test-responsesAreSame.mjs index 4168f626d..14f1ef8c9 100644 --- a/test/workbox-broadcast-update/sw/test-responsesAreSame.mjs +++ b/test/workbox-broadcast-update/sw/test-responsesAreSame.mjs @@ -8,13 +8,12 @@ import {responsesAreSame} from '../../../packages/workbox-broadcast-update/responsesAreSame.mjs'; - -describe(`responsesAreSame`, function() { +describe(`responsesAreSame`, function () { const firstHeaderName = 'x-first-header'; const secondHeaderName = 'x-second-header'; const headersToCheck = [firstHeaderName, secondHeaderName]; - it(`should throw when responsesAreSame() is called without any parameters`, function() { + it(`should throw when responsesAreSame() is called without any parameters`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -22,7 +21,7 @@ describe(`responsesAreSame`, function() { }, 'invalid-responses-are-same-args'); }); - it(`should return true when all the headers match`, function() { + it(`should return true when all the headers match`, function () { const first = new Response('', { headers: { [firstHeaderName]: 'same', @@ -35,14 +34,10 @@ describe(`responsesAreSame`, function() { [secondHeaderName]: 'same', }, }); - expect(responsesAreSame( - first, - second, - headersToCheck, - )).to.be.true; + expect(responsesAreSame(first, second, headersToCheck)).to.be.true; }); - it(`should return true when only a subset of headers exist, but the existing ones match`, function() { + it(`should return true when only a subset of headers exist, but the existing ones match`, function () { const first = new Response('', { headers: { [firstHeaderName]: 'same', @@ -53,24 +48,16 @@ describe(`responsesAreSame`, function() { [firstHeaderName]: 'same', }, }); - expect(responsesAreSame( - first, - second, - headersToCheck, - )).to.be.true; + expect(responsesAreSame(first, second, headersToCheck)).to.be.true; }); - it(`should return true when no headers exist`, function() { + it(`should return true when no headers exist`, function () { const first = new Response(''); const second = new Response(''); - expect(responsesAreSame( - first, - second, - headersToCheck, - )).to.be.true; + expect(responsesAreSame(first, second, headersToCheck)).to.be.true; }); - it(`should return false when one header matches and the other doesn't`, function() { + it(`should return false when one header matches and the other doesn't`, function () { const first = new Response('', { headers: { [firstHeaderName]: 'same', @@ -83,14 +70,10 @@ describe(`responsesAreSame`, function() { [secondHeaderName]: 'different', }, }); - expect(responsesAreSame( - first, - second, - headersToCheck, - )).to.be.false; + expect(responsesAreSame(first, second, headersToCheck)).to.be.false; }); - it(`should return false when none of the headers match`, function() { + it(`should return false when none of the headers match`, function () { const first = new Response('', { headers: { [firstHeaderName]: 'same', @@ -103,10 +86,6 @@ describe(`responsesAreSame`, function() { [secondHeaderName]: 'different', }, }); - expect(responsesAreSame( - first, - second, - headersToCheck, - )).to.be.false; + expect(responsesAreSame(first, second, headersToCheck)).to.be.false; }); }); diff --git a/test/workbox-build/node/dependency-check.js b/test/workbox-build/node/dependency-check.js index 4b2814234..5f936e6ed 100644 --- a/test/workbox-build/node/dependency-check.js +++ b/test/workbox-build/node/dependency-check.js @@ -9,54 +9,72 @@ const upath = require('upath'); const depcheck = require('depcheck'); -describe(`[workbox-build] Test Dependencies`, function() { - it(`should have required dependencies`, function() { +describe(`[workbox-build] Test Dependencies`, function () { + it(`should have required dependencies`, function () { return new Promise((resolve, reject) => { - depcheck(upath.join(__dirname, '..', '..', '..', 'packages', 'workbox-build'), { - ignoreDirs: [ - 'test', - 'build', - 'demo', - ], - ignoreMatches: [ - '@babel/preset-env', - '@babel/runtime', - 'type-fest', - 'workbox-background-sync', - 'workbox-broadcast-update', - 'workbox-cacheable-response', - 'workbox-core', - 'workbox-expiration', - 'workbox-google-analytics', - 'workbox-navigation-preload', - 'workbox-precaching', - 'workbox-range-requests', - 'workbox-recipes', - 'workbox-routing', - 'workbox-strategies', - 'workbox-streams', - 'workbox-sw', - 'workbox-window', - ], - }, (unusedDeps) => { - if (unusedDeps.dependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.dependencies)}`)); - } + depcheck( + upath.join(__dirname, '..', '..', '..', 'packages', 'workbox-build'), + { + ignoreDirs: ['test', 'build', 'demo'], + ignoreMatches: [ + '@babel/preset-env', + '@babel/runtime', + 'type-fest', + 'workbox-background-sync', + 'workbox-broadcast-update', + 'workbox-cacheable-response', + 'workbox-core', + 'workbox-expiration', + 'workbox-google-analytics', + 'workbox-navigation-preload', + 'workbox-precaching', + 'workbox-range-requests', + 'workbox-recipes', + 'workbox-routing', + 'workbox-strategies', + 'workbox-streams', + 'workbox-sw', + 'workbox-window', + ], + }, + (unusedDeps) => { + if (unusedDeps.dependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.dependencies, + )}`, + ), + ); + } - if (unusedDeps.devDependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.devDependencies)}`)); - } + if (unusedDeps.devDependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.devDependencies, + )}`, + ), + ); + } - if (Object.keys(unusedDeps.missing).length > 0) { - return reject(new Error(`Dependencies missing from package.json: ${JSON.stringify(unusedDeps.missing)}`)); - } + if (Object.keys(unusedDeps.missing).length > 0) { + return reject( + new Error( + `Dependencies missing from package.json: ${JSON.stringify( + unusedDeps.missing, + )}`, + ), + ); + } - resolve(); - }); + resolve(); + }, + ); }); }); - it(`should have no devDependencies`, function() { + it(`should have no devDependencies`, function () { // This test exists because there have been a number of situations where // dependencies have been used from the top level project and NOT from // this module itself. So dependencies are checked above and devDependencies diff --git a/test/workbox-build/node/generate-sw.js b/test/workbox-build/node/generate-sw.js index 0462a9b4e..908985c1e 100644 --- a/test/workbox-build/node/generate-sw.js +++ b/test/workbox-build/node/generate-sw.js @@ -13,15 +13,19 @@ const upath = require('upath'); const tempy = require('tempy'); const {errors} = require('../../../packages/workbox-build/build/lib/errors'); -const {generateSW} = require('../../../packages/workbox-build/build/generate-sw'); -const {WorkboxConfigError} = require('../../../packages/workbox-build/build/lib/validate-options'); +const { + generateSW, +} = require('../../../packages/workbox-build/build/generate-sw'); +const { + WorkboxConfigError, +} = require('../../../packages/workbox-build/build/lib/validate-options'); const confirmDirectoryContains = require('../../../infra/testing/confirm-directory-contains'); const validateServiceWorkerRuntime = require('../../../infra/testing/validator/service-worker-runtime'); chai.use(chaiAsPromised); const {expect} = chai; -describe(`[workbox-build] generate-sw.js (End to End)`, function() { +describe(`[workbox-build] generate-sw.js (End to End)`, function () { const GLOB_DIR = upath.join(__dirname, '..', 'static', 'example-project-1'); const BASE_OPTIONS = { globDirectory: GLOB_DIR, @@ -29,9 +33,7 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { mode: 'development', swDest: tempy.file({extension: 'js'}), }; - const REQUIRED_PARAMS = [ - 'swDest', - ]; + const REQUIRED_PARAMS = ['swDest']; const SUPPORTED_PARAMS = [ 'additionalManifestEntries', 'babelPresetEnvTargets', @@ -62,58 +64,62 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { 'sourcemap', 'templatedURLs', ].concat(REQUIRED_PARAMS); - const UNSUPPORTED_PARAMS = [ - 'injectionPoint', - 'swSrc', - ]; + const UNSUPPORTED_PARAMS = ['injectionPoint', 'swSrc']; - describe('[workbox-build] required parameters', function() { + describe('[workbox-build] required parameters', function () { for (const requiredParam of REQUIRED_PARAMS) { - it(`should fail validation when '${requiredParam}' is missing`, async function() { + it(`should fail validation when '${requiredParam}' is missing`, async function () { const options = Object.assign({}, BASE_OPTIONS); delete options[requiredParam]; await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, requiredParam); + WorkboxConfigError, + requiredParam, + ); }); } }); - describe('[workbox-build] unsupported parameters', function() { + describe('[workbox-build] unsupported parameters', function () { for (const unsupportedParam of UNSUPPORTED_PARAMS) { - it(`should fail validation when '${unsupportedParam}' is present`, async function() { + it(`should fail validation when '${unsupportedParam}' is present`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[unsupportedParam] = unsupportedParam; await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, unsupportedParam); + WorkboxConfigError, + unsupportedParam, + ); }); } }); - describe('[workbox-build] invalid parameter values', function() { + describe('[workbox-build] invalid parameter values', function () { for (const param of SUPPORTED_PARAMS) { - it(`should fail validation when '${param}' is an unexpected value`, async function() { + it(`should fail validation when '${param}' is an unexpected value`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[param] = () => {}; await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, param); + WorkboxConfigError, + param, + ); }); } - it(`should reject when there are no manifest entries or runtimeCaching`, async function() { + it(`should reject when there are no manifest entries or runtimeCaching`, async function () { const options = Object.assign({}, BASE_OPTIONS); // This temporary directory will be empty. options.globDirectory = tempy.directory(); await expect(generateSW(options)).to.eventually.be.rejectedWith( - errors['no-manifest-entries-or-runtime-caching']); + errors['no-manifest-entries-or-runtime-caching'], + ); }); }); - describe(`[workbox-build] writing a service worker file`, function() { - it(`should use defaults when all the required parameters are present`, async function() { + describe(`[workbox-build] writing a service worker file`, function () { + it(`should use defaults when all the required parameters are present`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, {swDest}); @@ -122,36 +128,51 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - __WB_DISABLE_DEV_LOGS: undefined, - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + __WB_DISABLE_DEV_LOGS: undefined, + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); - it(`should include the versioning strings in the generated bundle`, async function() { + it(`should include the versioning strings in the generated bundle`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -168,7 +189,7 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(contents).to.include(`workbox:core:`); }); - it(`should disable logging when disableDevLogs is set to true`, async function() { + it(`should disable logging when disableDevLogs is set to true`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -180,36 +201,51 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - __WB_DISABLE_DEV_LOGS: true, - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + __WB_DISABLE_DEV_LOGS: true, + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); - it(`should use defaults when all the required parameters are present, with additional importScripts`, async function() { + it(`should use defaults when all the required parameters are present, with additional importScripts`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const importScripts = ['manifest.js']; @@ -222,38 +258,50 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [ - [/^\.\/workbox-[0-9a-f]{8}$/], - [...importScripts], - ], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/], [...importScripts]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); - it(`should use defaults when all the required parameters are present, with additional configuration`, async function() { + it(`should use defaults when all the required parameters are present, with additional configuration`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const directoryIndex = 'test.html'; @@ -266,47 +314,65 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { clientsClaim: true, skipWaiting: true, }; - const options = Object.assign({}, BASE_OPTIONS, additionalOptions, {swDest}); + const options = Object.assign({}, BASE_OPTIONS, additionalOptions, { + swDest, + }); const {count, filePaths, size, warnings} = await generateSW(options); expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - clientsClaim: [[]], - skipWaiting: [[]], - setCacheNameDetails: [[{prefix: cacheId}]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {directoryIndex, ignoreURLParametersMatching}]], - }, addEventListenerValidation: (addEventListenerStub) => { - // When skipWaiting is true, the 'message' addEventListener shouldn't be called. - expect(addEventListenerStub.called).to.be.false; - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + clientsClaim: [[]], + skipWaiting: [[]], + setCacheNameDetails: [[{prefix: cacheId}]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {directoryIndex, ignoreURLParametersMatching}, + ], + ], + }, + addEventListenerValidation: (addEventListenerStub) => { + // When skipWaiting is true, the 'message' addEventListener shouldn't be called. + expect(addEventListenerStub.called).to.be.false; + }, + }); }); - it(`should use defaults when all the required parameters are present, with additionalManifestEntries`, async function() { + it(`should use defaults when all the required parameters are present, with additionalManifestEntries`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -325,95 +391,134 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.have.length(1); expect(count).to.eql(10); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }, { - revision: null, - url: '/one', - }, { - revision: null, - url: '/two', - }, { - revision: '333', - url: '/three', - }, { - url: '/four', - revision: '123', - integrity: '456', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + { + revision: null, + url: '/one', + }, + { + revision: null, + url: '/two', + }, + { + revision: '333', + url: '/three', + }, + { + url: '/four', + revision: '123', + integrity: '456', + }, + ], + {}, + ], + ], + }, + }); }); - it(`should add a 'message' event listener when 'skipWaiting: false'`, async function() { + it(`should add a 'message' event listener when 'skipWaiting: false'`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const additionalOptions = { skipWaiting: false, }; - const options = Object.assign({}, BASE_OPTIONS, additionalOptions, {swDest}); + const options = Object.assign({}, BASE_OPTIONS, additionalOptions, { + swDest, + }); const {count, filePaths, size, warnings} = await generateSW(options); expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }, addEventListenerValidation: (addEventListenerStub) => { - expect(addEventListenerStub.calledOnce).to.be.true; - expect(addEventListenerStub.firstCall.args[0]).to.eql('message'); - // This isn't the *cleanest* possible way of testing the message event - // handler, but given the constraints of this node-based environment, - // it seems the most effective way to ensure the right code gets run. - expect(addEventListenerStub.firstCall.args[1].toString()).to.eql(`event => {\n if (event.data && event.data.type === 'SKIP_WAITING') {\n self.skipWaiting();\n }\n }`); - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + addEventListenerValidation: (addEventListenerStub) => { + expect(addEventListenerStub.calledOnce).to.be.true; + expect(addEventListenerStub.firstCall.args[0]).to.eql('message'); + // This isn't the *cleanest* possible way of testing the message event + // handler, but given the constraints of this node-based environment, + // it seems the most effective way to ensure the right code gets run. + expect(addEventListenerStub.firstCall.args[1].toString()).to.eql( + `event => {\n if (event.data && event.data.type === 'SKIP_WAITING') {\n self.skipWaiting();\n }\n }`, + ); + }, + }); }); - it(`should use defaults when all the required parameters are present, with 'navigateFallback'`, async function() { + it(`should use defaults when all the required parameters are present, with 'navigateFallback'`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const navigateFallback = 'test.html'; @@ -430,41 +535,61 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - createHandlerBoundToURL: [[navigateFallback]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - registerRoute: [[{name: 'NavigationRoute'}]], - NavigationRoute: [['/urlWithCacheKey', { - denylist: navigateFallbackDenylist, - allowlist: navigateFallbackAllowlist, - }]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + createHandlerBoundToURL: [[navigateFallback]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + registerRoute: [[{name: 'NavigationRoute'}]], + NavigationRoute: [ + [ + '/urlWithCacheKey', + { + denylist: navigateFallbackDenylist, + allowlist: navigateFallbackAllowlist, + }, + ], + ], + }, + }); }); - it(`should use defaults when all the required parameters are present, with symlinks`, async function() { + it(`should use defaults when all the required parameters are present, with symlinks`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const globDirectory = tempy.directory(); @@ -480,35 +605,50 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'link/index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'link/index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); - it(`should use defaults when all the required parameters are present, with 'globFollow' and symlinks`, async function() { + it(`should use defaults when all the required parameters are present, with 'globFollow' and symlinks`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const globDirectory = tempy.directory(); @@ -525,29 +665,42 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(4); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2535, 2611]); + expect(size).to.be.oneOf([2707, 2629]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'link/index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'link/index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); - it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to true`, async function() { + it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to true`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -559,36 +712,51 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - initialize: [[{}]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + initialize: [[{}]], + }, + }); }); - it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to a config`, async function() { + it(`should use defaults when all the required parameters are present, with 'offlineGoogleAnalytics' set to a config`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -604,40 +772,59 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - initialize: [[{ - parameterOverrides: { - cd1: 'offline', - }, - }]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + initialize: [ + [ + { + parameterOverrides: { + cd1: 'offline', + }, + }, + ], + ], + }, + }); }); - it(`should support using a swDest that includes a subdirectory`, async function() { + it(`should support using a swDest that includes a subdirectory`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sub', 'directory', 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -648,12 +835,12 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); }); - it(`should inline the Workbox runtime when 'inlineWorkboxRuntime' is true`, async function() { + it(`should inline the Workbox runtime when 'inlineWorkboxRuntime' is true`, async function () { const outputDir = tempy.directory(); const swDest = upath.join(outputDir, 'sw.js'); const options = Object.assign({}, BASE_OPTIONS, { @@ -665,60 +852,70 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await confirmDirectoryContains(outputDir, filePaths); // We can't validate the generated sw.js file, unfortunately. }); }); - describe(`[workbox-build] behavior with 'runtimeCaching'`, function() { + describe(`[workbox-build] behavior with 'runtimeCaching'`, function () { const DEFAULT_METHOD = 'GET'; const REGEXP_URL_PATTERN = /test/; const STRING_URL_PATTERN = '/test'; const STRING_HANDLER = 'CacheFirst'; const FUNCTION_URL_PATTERN = (params) => true; - it(`should reject when 'urlPattern' is missing from 'runtimeCaching'`, async function() { + it(`should reject when 'urlPattern' is missing from 'runtimeCaching'`, async function () { const handler = STRING_HANDLER; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching: [{handler}], }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, 'urlPattern'); + WorkboxConfigError, + 'urlPattern', + ); }); - it(`should reject when 'handler' is missing from 'runtimeCaching'`, async function() { + it(`should reject when 'handler' is missing from 'runtimeCaching'`, async function () { const urlPattern = REGEXP_URL_PATTERN; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching: [{urlPattern}], }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, 'handler'); + WorkboxConfigError, + 'handler', + ); }); - it(`should reject when 'handler' is not a valid strategy name`, async function() { + it(`should reject when 'handler' is not a valid strategy name`, async function () { const urlPattern = REGEXP_URL_PATTERN; const options = Object.assign({}, BASE_OPTIONS, { - runtimeCaching: [{ - urlPattern, - handler: 'invalid', - }], + runtimeCaching: [ + { + urlPattern, + handler: 'invalid', + }, + ], }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, 'handler'); + WorkboxConfigError, + 'handler', + ); }); // See https://github.com/GoogleChrome/workbox/issues/2078 - it(`should not require using precaching`, async function() { + it(`should not require using precaching`, async function () { const swDest = tempy.file({extension: 'js'}); - const runtimeCaching = [{ - urlPattern: STRING_URL_PATTERN, - handler: STRING_HANDLER, - }]; + const runtimeCaching = [ + { + urlPattern: STRING_URL_PATTERN, + handler: STRING_HANDLER, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -729,19 +926,26 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(0); expect(size).to.eql(0); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [STRING_HANDLER]: [[]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - registerRoute: [[STRING_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD]], - }}); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [STRING_HANDLER]: [[]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + registerRoute: [ + [STRING_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], + ], + }, + }); }); - it(`should support a single string 'urlPattern' and a string 'handler'`, async function() { + it(`should support a single string 'urlPattern' and a string 'handler'`, async function () { const swDest = tempy.file({extension: 'js'}); - const runtimeCaching = [{ - urlPattern: STRING_URL_PATTERN, - handler: STRING_HANDLER, - }]; + const runtimeCaching = [ + { + urlPattern: STRING_URL_PATTERN, + handler: STRING_HANDLER, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -751,39 +955,58 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [STRING_HANDLER]: [[]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - registerRoute: [[STRING_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD]], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [STRING_HANDLER]: [[]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + registerRoute: [ + [STRING_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], + ], + }, + }); }); - it(`should support a single function 'urlPattern' and a string 'handler'`, async function() { + it(`should support a single function 'urlPattern' and a string 'handler'`, async function () { const swDest = tempy.file({extension: 'js'}); - const runtimeCaching = [{ - urlPattern: FUNCTION_URL_PATTERN, - handler: STRING_HANDLER, - }]; + const runtimeCaching = [ + { + urlPattern: FUNCTION_URL_PATTERN, + handler: STRING_HANDLER, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -793,35 +1016,52 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [STRING_HANDLER]: [[]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - // See https://github.com/chaijs/chai/issues/697 - registerRoute: [['params => true', {name: STRING_HANDLER}, DEFAULT_METHOD]], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [STRING_HANDLER]: [[]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + // See https://github.com/chaijs/chai/issues/697 + registerRoute: [ + ['params => true', {name: STRING_HANDLER}, DEFAULT_METHOD], + ], + }, + }); }); - it(`should support setting individual 'options' each, for multiple 'runtimeCaching' entries`, async function() { + it(`should support setting individual 'options' each, for multiple 'runtimeCaching' entries`, async function () { const swDest = tempy.file({extension: 'js'}); const firstRuntimeCachingOptions = { cacheName: 'first-cache-name', @@ -843,15 +1083,18 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { fallbackURL: '/test', }, }; - const runtimeCaching = [{ - urlPattern: REGEXP_URL_PATTERN, - handler: STRING_HANDLER, - options: firstRuntimeCachingOptions, - }, { - urlPattern: REGEXP_URL_PATTERN, - handler: STRING_HANDLER, - options: secondRuntimeCachingOptions, - }]; + const runtimeCaching = [ + { + urlPattern: REGEXP_URL_PATTERN, + handler: STRING_HANDLER, + options: firstRuntimeCachingOptions, + }, + { + urlPattern: REGEXP_URL_PATTERN, + handler: STRING_HANDLER, + options: secondRuntimeCachingOptions, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -862,66 +1105,95 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [STRING_HANDLER]: [[{ - cacheName: firstRuntimeCachingOptions.cacheName, - plugins: [{}], - }], [{ - cacheName: secondRuntimeCachingOptions.cacheName, - plugins: [{}, {}], - }]], - ExpirationPlugin: [[firstRuntimeCachingOptions.expiration]], - CacheableResponsePlugin: [[secondRuntimeCachingOptions.cacheableResponse]], - PrecacheFallbackPlugin: [[secondRuntimeCachingOptions.precacheFallback]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - registerRoute: [ - [REGEXP_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], - [REGEXP_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], - ], - }}); + expect(size).to.be.oneOf([2782, 2698]); + + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [STRING_HANDLER]: [ + [ + { + cacheName: firstRuntimeCachingOptions.cacheName, + plugins: [{}], + }, + ], + [ + { + cacheName: secondRuntimeCachingOptions.cacheName, + plugins: [{}, {}], + }, + ], + ], + ExpirationPlugin: [[firstRuntimeCachingOptions.expiration]], + CacheableResponsePlugin: [ + [secondRuntimeCachingOptions.cacheableResponse], + ], + PrecacheFallbackPlugin: [ + [secondRuntimeCachingOptions.precacheFallback], + ], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + registerRoute: [ + [REGEXP_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], + [REGEXP_URL_PATTERN, {name: STRING_HANDLER}, DEFAULT_METHOD], + ], + }, + }); }); - it(`should reject with a ValidationError when 'networkTimeoutSeconds' is used and handler is not 'NetworkFirst'`, async function() { + it(`should reject with a ValidationError when 'networkTimeoutSeconds' is used and handler is not 'NetworkFirst'`, async function () { const swDest = tempy.file({extension: 'js'}); const runtimeCachingOptions = { networkTimeoutSeconds: 1, }; - const runtimeCaching = [{ - urlPattern: REGEXP_URL_PATTERN, - handler: 'NetworkOnly', - options: runtimeCachingOptions, - }]; + const runtimeCaching = [ + { + urlPattern: REGEXP_URL_PATTERN, + handler: 'NetworkOnly', + options: runtimeCachingOptions, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - errors['invalid-network-timeout-seconds']); + errors['invalid-network-timeout-seconds'], + ); }); - it(`should support passing in a function when allowed`, async function() { + it(`should support passing in a function when allowed`, async function () { const swDest = tempy.file({extension: 'js'}); const handler = () => {}; const urlPattern = () => {}; @@ -933,15 +1205,19 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { onSync: () => {}, }, }, - plugins: [{ - cachedResponseWillBeUsed: () => {}, - }], + plugins: [ + { + cachedResponseWillBeUsed: () => {}, + }, + ], }; - const runtimeCaching = [{ - handler, - urlPattern, - options: runtimeCachingOptions, - }]; + const runtimeCaching = [ + { + handler, + urlPattern, + options: runtimeCachingOptions, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -951,36 +1227,51 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [handler]: [[runtimeCachingOptions]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - registerRoute: [ - [urlPattern.toString(), handler.toString(), DEFAULT_METHOD], - ], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [handler]: [[runtimeCachingOptions]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + registerRoute: [ + [urlPattern.toString(), handler.toString(), DEFAULT_METHOD], + ], + }, + }); }); - it(`should support 'networkTimeoutSeconds' when handler is 'NetworkFirst'`, async function() { + it(`should support 'networkTimeoutSeconds' when handler is 'NetworkFirst'`, async function () { const swDest = tempy.file({extension: 'js'}); const networkTimeoutSeconds = 1; const handler = 'NetworkFirst'; @@ -989,11 +1280,13 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { networkTimeoutSeconds, plugins: [], }; - const runtimeCaching = [{ - urlPattern: REGEXP_URL_PATTERN, - handler, - options: runtimeCachingOptions, - }]; + const runtimeCaching = [ + { + urlPattern: REGEXP_URL_PATTERN, + handler, + options: runtimeCachingOptions, + }, + ]; const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching, swDest, @@ -1003,54 +1296,73 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [handler]: [[runtimeCachingOptions]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - registerRoute: [ - [REGEXP_URL_PATTERN, {name: handler}, DEFAULT_METHOD], - ], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [handler]: [[runtimeCachingOptions]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + registerRoute: [ + [REGEXP_URL_PATTERN, {name: handler}, DEFAULT_METHOD], + ], + }, + }); }); - it(`should reject when 'options.expiration' is used without 'options.cacheName'`, async function() { + it(`should reject when 'options.expiration' is used without 'options.cacheName'`, async function () { const urlPattern = REGEXP_URL_PATTERN; const options = Object.assign({}, BASE_OPTIONS, { - runtimeCaching: [{ - urlPattern, - handler: 'NetworkFirst', - options: { - expiration: { - maxEntries: 5, + runtimeCaching: [ + { + urlPattern, + handler: 'NetworkFirst', + options: { + expiration: { + maxEntries: 5, + }, }, }, - }], + ], }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, errors['cache-name-required']); + WorkboxConfigError, + errors['cache-name-required'], + ); }); - it(`should ignore swDest and workbox-*.js when generating manifest entries`, async function() { + it(`should ignore swDest and workbox-*.js when generating manifest entries`, async function () { const tempDirectory = tempy.directory(); await fse.copy(BASE_OPTIONS.globDirectory, tempDirectory); const swDest = upath.join(tempDirectory, 'service-worker.js'); @@ -1066,53 +1378,72 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + }, + }); }); }); - describe(`[workbox-build] behavior with 'navigationPreload'`, function() { - it(`should reject when 'navigationPreload' is true and 'runtimeCaching' is undefined`, async function() { + describe(`[workbox-build] behavior with 'navigationPreload'`, function () { + it(`should reject when 'navigationPreload' is true and 'runtimeCaching' is undefined`, async function () { const options = Object.assign({}, BASE_OPTIONS, { navigationPreload: true, }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, errors['nav-preload-runtime-caching']); + WorkboxConfigError, + errors['nav-preload-runtime-caching'], + ); }); - it(`should reject when 'navigationPreload' is true and 'runtimeCaching' is undefined`, async function() { + it(`should reject when 'navigationPreload' is true and 'runtimeCaching' is undefined`, async function () { const options = Object.assign({}, BASE_OPTIONS, { runtimeCaching: undefined, navigationPreload: true, }); await expect(generateSW(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, errors['nav-preload-runtime-caching']); + WorkboxConfigError, + errors['nav-preload-runtime-caching'], + ); }); - it(`should generate when 'navigationPreload' is true and 'runtimeCaching' is valid`, async function() { + it(`should generate when 'navigationPreload' is true and 'runtimeCaching' is valid`, async function () { const swDest = tempy.file({extension: 'js'}); const urlPattern = /test/; const handler = 'CacheFirst'; @@ -1126,32 +1457,47 @@ describe(`[workbox-build] generate-sw.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); - await validateServiceWorkerRuntime({swFile: swDest, expectedMethodCalls: { - [handler]: [[]], - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], {}]], - enable: [[]], - registerRoute: [[urlPattern, {name: handler}, 'GET']], - }}); + expect(size).to.be.oneOf([2782, 2698]); + await validateServiceWorkerRuntime({ + swFile: swDest, + expectedMethodCalls: { + [handler]: [[]], + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + {}, + ], + ], + enable: [[]], + registerRoute: [[urlPattern, {name: handler}, 'GET']], + }, + }); }); }); }); diff --git a/test/workbox-build/node/get-manifest.js b/test/workbox-build/node/get-manifest.js index 6c8cd0f26..1b261ddfa 100644 --- a/test/workbox-build/node/get-manifest.js +++ b/test/workbox-build/node/get-manifest.js @@ -17,10 +17,14 @@ chai.use(chaiAsPromised); chai.use(chaiMatchPattern); const {expect} = chai; -const {getManifest} = require('../../../packages/workbox-build/build/get-manifest'); -const {WorkboxConfigError} = require('../../../packages/workbox-build/build/lib/validate-options'); - -describe(`[workbox-build] get-manifest.js (End to End)`, function() { +const { + getManifest, +} = require('../../../packages/workbox-build/build/get-manifest'); +const { + WorkboxConfigError, +} = require('../../../packages/workbox-build/build/lib/validate-options'); + +describe(`[workbox-build] get-manifest.js (End to End)`, function () { const SRC_DIR = upath.join(__dirname, '..', 'static', 'example-project-1'); const BASE_OPTIONS = { globDirectory: SRC_DIR, @@ -54,193 +58,250 @@ describe(`[workbox-build] get-manifest.js (End to End)`, function() { 'swDest', ]; - describe('[workbox-build] unsupported parameters', function() { + describe('[workbox-build] unsupported parameters', function () { for (const unsupportedParam of UNSUPPORTED_PARAMS) { - it(`should fail validation when '${unsupportedParam}' is present`, async function() { + it(`should fail validation when '${unsupportedParam}' is present`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[unsupportedParam] = unsupportedParam; await expect(getManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, unsupportedParam); + WorkboxConfigError, + unsupportedParam, + ); }); } }); - describe('[workbox-build] invalid parameter values', function() { + describe('[workbox-build] invalid parameter values', function () { for (const param of SUPPORTED_PARAMS) { - it(`should fail validation when '${param}' is an unexpected value`, async function() { + it(`should fail validation when '${param}' is an unexpected value`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[param] = () => {}; await expect(getManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, param); + WorkboxConfigError, + param, + ); }); } }); - describe('[workbox-build] should generate a valid manifest when properly configured', function() { - it(`should use defaults when all the required parameters are present`, async function() { + describe('[workbox-build] should generate a valid manifest when properly configured', function () { + it(`should use defaults when all the required parameters are present`, async function () { const options = Object.assign({}, BASE_OPTIONS); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); }); - it(`should use defaults when all the required parameters, and 'globPatterns' are present`, async function() { + it(`should use defaults when all the required parameters, and 'globPatterns' are present`, async function () { const options = Object.assign({}, BASE_OPTIONS, { globPatterns: ['**/*.html', '**/*.js'], }); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(4); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2535, 2611]); + expect(size).to.be.oneOf([2707, 2629]); }); - it(`should use defaults when all the required parameters, and 'globIgnores' are present`, async function() { - const options = Object.assign({ - globIgnores: ['**/*.html', '**/*.js'], - }, BASE_OPTIONS); + it(`should use defaults when all the required parameters, and 'globIgnores' are present`, async function () { + const options = Object.assign( + { + globIgnores: ['**/*.html', '**/*.js'], + }, + BASE_OPTIONS, + ); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(2); // Line ending differences lead to different sizes on Windows. expect(size).to.be.oneOf([69, 75]); }); - it(`should use defaults when all the required parameters, 'globIgnores', and 'globPatterns' are present`, async function() { + it(`should use defaults when all the required parameters, 'globIgnores', and 'globPatterns' are present`, async function () { const options = Object.assign({}, BASE_OPTIONS, { globPatterns: ['**/*.css', '**/*.js'], globIgnores: ['node_modules/**/*', '**/*2*'], }); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(2); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([217, 220]); + expect(size).to.be.oneOf([216, 219]); }); - it(`should use defaults when all the required parameters, and 'maximumFileSizeToCacheInBytes' are present`, async function() { - const options = Object.assign({ - maximumFileSizeToCacheInBytes: 50, - }, BASE_OPTIONS); + it(`should use defaults when all the required parameters, and 'maximumFileSizeToCacheInBytes' are present`, async function () { + const options = Object.assign( + { + maximumFileSizeToCacheInBytes: 50, + }, + BASE_OPTIONS, + ); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.have.lengthOf(2); - expect(manifestEntries).to.matchPattern([{ - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }]); + expect(manifestEntries).to.matchPattern([ + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + ]); expect(count).to.eql(4); // Line ending differences lead to different sizes on Windows. expect(size).to.be.oneOf([101, 109]); }); - it(`should use defaults when all the required parameters, and 'templatedURLs' are present`, async function() { + it(`should use defaults when all the required parameters, and 'templatedURLs' are present`, async function () { const url1 = 'url1'; const url2 = 'url2'; - const options = Object.assign({ - templatedURLs: { - [url1]: ['**/*.html'], - [url2]: 'string dependency', + const options = Object.assign( + { + templatedURLs: { + [url1]: ['**/*.html'], + [url2]: 'string dependency', + }, }, - }, BASE_OPTIONS); + BASE_OPTIONS, + ); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'url1', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'url2', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'url1', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'url2', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(8); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([4973, 5131]); + expect(size).to.be.oneOf([5162, 5324]); }); - it(`should use defaults when all the required parameters, and 'manifestTransforms' are present`, async function() { + it(`should use defaults when all the required parameters, and 'manifestTransforms' are present`, async function () { // This filters out all entries unless the url property includes the string '1'. const transform1 = (entries) => { const manifest = entries.filter((entry) => { @@ -257,25 +318,33 @@ describe(`[workbox-build] get-manifest.js (End to End)`, function() { return {manifest}; }; - const options = Object.assign({ - manifestTransforms: [transform1, transform2], - }, BASE_OPTIONS); + const options = Object.assign( + { + manifestTransforms: [transform1, transform2], + }, + BASE_OPTIONS, + ); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: '/prefix/page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: '/prefix/styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: '/prefix/page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: '/prefix/styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(2); // Line ending differences lead to different sizes on Windows. expect(size).to.be.oneOf([50, 54]); }); - it(`should use defaults when all the required parameters are present, with 'globFollow' and symlinks`, async function() { + it(`should use defaults when all the required parameters are present, with 'globFollow' and symlinks`, async function () { const globDirectory = tempy.directory(); await fse.ensureSymlink(SRC_DIR, upath.join(globDirectory, 'link')); @@ -285,28 +354,35 @@ describe(`[workbox-build] get-manifest.js (End to End)`, function() { globFollow: false, }); - const {count, size, manifestEntries, warnings} = await getManifest(options); + const {count, size, manifestEntries, warnings} = await getManifest( + options, + ); expect(warnings).to.be.empty; - expect(manifestEntries).to.matchPattern([{ - url: 'link/index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'link/webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]); + expect(manifestEntries).to.matchPattern([ + { + url: 'link/index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'link/webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ]); expect(count).to.eql(4); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2535, 2611]); + expect(size).to.be.oneOf([2707, 2629]); }); }); - describe(`[workbox-build] removed options`, function() { + describe(`[workbox-build] removed options`, function () { // These were deprecated in v4, and formally removed in v5. const oldOptionsToValue = { dontCacheBustUrlsMatching: /ignored/, @@ -318,13 +394,15 @@ describe(`[workbox-build] get-manifest.js (End to End)`, function() { }; for (const [option, value] of Object.entries(oldOptionsToValue)) { - it(`should fail validation when ${option} is used`, async function() { + it(`should fail validation when ${option} is used`, async function () { const options = Object.assign({}, BASE_OPTIONS, { [option]: value, }); await expect(getManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, option); + WorkboxConfigError, + option, + ); }); } }); diff --git a/test/workbox-build/node/inject-manifest.js b/test/workbox-build/node/inject-manifest.js index 1af047230..aa3479ce7 100644 --- a/test/workbox-build/node/inject-manifest.js +++ b/test/workbox-build/node/inject-manifest.js @@ -13,14 +13,18 @@ const upath = require('upath'); const tempy = require('tempy'); const {errors} = require('../../../packages/workbox-build/build/lib/errors'); -const {injectManifest} = require('../../../packages/workbox-build/build/inject-manifest'); -const {WorkboxConfigError} = require('../../../packages/workbox-build/build/lib/validate-options'); +const { + injectManifest, +} = require('../../../packages/workbox-build/build/inject-manifest'); +const { + WorkboxConfigError, +} = require('../../../packages/workbox-build/build/lib/validate-options'); const validateServiceWorkerRuntime = require('../../../infra/testing/validator/service-worker-runtime'); chai.use(chaiAsPromised); const {expect} = chai; -describe(`[workbox-build] inject-manifest.js (End to End)`, function() { +describe(`[workbox-build] inject-manifest.js (End to End)`, function () { const GLOB_DIR = upath.join(__dirname, '..', 'static', 'example-project-1'); const SW_SRC_DIR = upath.join(__dirname, '..', 'static', 'sw-injections'); const BASE_OPTIONS = { @@ -28,10 +32,7 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { swDest: tempy.file({extension: 'js'}), swSrc: upath.join(SW_SRC_DIR, 'basic.js'), }; - const REQUIRED_PARAMS = [ - 'swDest', - 'swSrc', - ]; + const REQUIRED_PARAMS = ['swDest', 'swSrc']; const SUPPORTED_PARAMS = [ 'additionalManifestEntries', 'dontCacheBustURLsMatching', @@ -60,62 +61,70 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { 'skipWaiting', ]; - describe('[workbox-build] required parameters', function() { + describe('[workbox-build] required parameters', function () { for (const requiredParam of REQUIRED_PARAMS) { - it(`should reject when '${requiredParam}' is missing`, async function() { + it(`should reject when '${requiredParam}' is missing`, async function () { const options = Object.assign({}, BASE_OPTIONS); delete options[requiredParam]; await expect(injectManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, requiredParam); + WorkboxConfigError, + requiredParam, + ); }); } }); - describe('[workbox-build] unsupported parameters', function() { + describe('[workbox-build] unsupported parameters', function () { for (const unsupportedParam of UNSUPPORTED_PARAMS) { - it(`should reject when '${unsupportedParam}' is present`, async function() { + it(`should reject when '${unsupportedParam}' is present`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[unsupportedParam] = unsupportedParam; await expect(injectManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, unsupportedParam); + WorkboxConfigError, + unsupportedParam, + ); }); } }); - describe('[workbox-build] invalid parameter values', function() { + describe('[workbox-build] invalid parameter values', function () { for (const param of SUPPORTED_PARAMS) { - it(`should reject when '${param}' is null`, async function() { + it(`should reject when '${param}' is null`, async function () { const options = Object.assign({}, BASE_OPTIONS); options[param] = null; await expect(injectManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, param); + WorkboxConfigError, + param, + ); }); } }); - describe(`[workbox-build] runtime errors`, function() { - it(`should throw the expected error when 'swSrc' is invalid`, async function() { + describe(`[workbox-build] runtime errors`, function () { + it(`should throw the expected error when 'swSrc' is invalid`, async function () { const options = Object.assign({}, BASE_OPTIONS, { swSrc: 'DOES_NOT_EXIST', }); await expect(injectManifest(options)).to.eventually.be.rejectedWith( - errors['invalid-sw-src']); + errors['invalid-sw-src'], + ); }); - it(`should throw the expected error when there is no match for 'injectionPoint'`, async function() { + it(`should throw the expected error when there is no match for 'injectionPoint'`, async function () { const options = Object.assign({}, BASE_OPTIONS, { swSrc: upath.join(SW_SRC_DIR, 'bad-no-injection.js'), }); await expect(injectManifest(options)).to.eventually.be.rejectedWith( - errors['injection-point-not-found']); + errors['injection-point-not-found'], + ); }); - it(`should throw the expected error when there is no match for 'injectionPoint' and 'swSrc' and 'swDest' are the same`, async function() { + it(`should throw the expected error when there is no match for 'injectionPoint' and 'swSrc' and 'swDest' are the same`, async function () { const swFile = upath.join(SW_SRC_DIR, 'bad-no-injection.js'); const options = Object.assign({}, BASE_OPTIONS, { swSrc: swFile, @@ -123,21 +132,23 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { }); await expect(injectManifest(options)).to.eventually.be.rejectedWith( - errors['same-src-and-dest']); + errors['same-src-and-dest'], + ); }); - it(`should throw the expected error when there are multiple matches for 'injectionPoint'`, async function() { + it(`should throw the expected error when there are multiple matches for 'injectionPoint'`, async function () { const options = Object.assign({}, BASE_OPTIONS, { swSrc: upath.join(SW_SRC_DIR, 'bad-multiple-injection.js'), }); await expect(injectManifest(options)).to.eventually.be.rejectedWith( - errors['multiple-injection-points']); + errors['multiple-injection-points'], + ); }); }); - describe(`[workbox-build] writing a service worker file`, function() { - it(`should use defaults when all the required parameters are present`, async function() { + describe(`[workbox-build] writing a service worker file`, function () { + it(`should use defaults when all the required parameters are present`, async function () { const swDest = tempy.file({extension: 'js'}); const options = Object.assign({}, BASE_OPTIONS, {swDest}); @@ -145,37 +156,48 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); expect(filePaths).to.have.members([upath.resolve(swDest)]); await validateServiceWorkerRuntime({ entryPoint: 'injectManifest', swFile: swDest, expectedMethodCalls: { - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + ], + ], }, }); }); - it(`should use absolute paths in the filePaths return value`, async function() { + it(`should use absolute paths in the filePaths return value`, async function () { // Deliberately use a relative path for swDest. const swDest = upath.relative('.', tempy.file({extension: 'js'})); const options = Object.assign({}, BASE_OPTIONS, {swDest}); @@ -186,7 +208,7 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(filePaths).to.have.members([upath.resolve(swDest)]); }); - it(`should use defaults when all the required parameters are present, when workboxSW.precache() is called twice`, async function() { + it(`should use defaults when all the required parameters are present, when workboxSW.precache() is called twice`, async function () { const swDest = tempy.file({extension: 'js'}); const options = Object.assign({}, BASE_OPTIONS, { swDest, @@ -197,7 +219,7 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); expect(filePaths).to.have.members([upath.resolve(swDest)]); await validateServiceWorkerRuntime({ @@ -205,33 +227,47 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { swFile: swDest, expectedMethodCalls: { importScripts: [['./sample-import.js']], - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]], [[ - '/extra-assets/example.1234.css', - '/extra-assets/example-2.1234.js', - ]]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + ], + [ + [ + '/extra-assets/example.1234.css', + '/extra-assets/example-2.1234.js', + ], + ], + ], }, }); }); - it(`should use defaults when all the required parameters are present, when a custom 'injectionPoint' is used`, async function() { + it(`should use defaults when all the required parameters are present, when a custom 'injectionPoint' is used`, async function () { const swDest = tempy.file({extension: 'js'}); const options = Object.assign({}, BASE_OPTIONS, { swDest, @@ -243,37 +279,48 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); expect(filePaths).to.have.members([upath.resolve(swDest)]); await validateServiceWorkerRuntime({ entryPoint: 'injectManifest', swFile: swDest, expectedMethodCalls: { - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + ], + ], }, }); }); - it(`should support using the default 'injectionPoint' when precacheAndRoute() is called with options`, async function() { + it(`should support using the default 'injectionPoint' when precacheAndRoute() is called with options`, async function () { const swDest = tempy.file({extension: 'js'}); const options = Object.assign({}, BASE_OPTIONS, { swDest, @@ -284,39 +331,51 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); expect(filePaths).to.have.members([upath.resolve(swDest)]); await validateServiceWorkerRuntime({ entryPoint: 'injectManifest', swFile: swDest, expectedMethodCalls: { - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }], { - cleanURLs: true, - }]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + { + cleanURLs: true, + }, + ], + ], }, }); }); - it(`should ignore swSrc and swDest when generating manifest entries`, async function() { + it(`should ignore swSrc and swDest when generating manifest entries`, async function () { const tempDirectory = tempy.directory(); await fse.copy(BASE_OPTIONS.globDirectory, tempDirectory); const swSrc = upath.join(tempDirectory, 'sw-src-service-worker.js'); @@ -333,41 +392,55 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); await validateServiceWorkerRuntime({ entryPoint: 'injectManifest', swFile: swDest, expectedMethodCalls: { - precacheAndRoute: [[[{ - url: 'index.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-1.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'page-2.html', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-1.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'styles/stylesheet-2.css', - revision: /^[0-9a-f]{32}$/, - }, { - url: 'webpackEntry.js', - revision: /^[0-9a-f]{32}$/, - }]]], + precacheAndRoute: [ + [ + [ + { + url: 'index.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-1.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'page-2.html', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-1.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'styles/stylesheet-2.css', + revision: /^[0-9a-f]{32}$/, + }, + { + url: 'webpackEntry.js', + revision: /^[0-9a-f]{32}$/, + }, + ], + ], + ], }, }); }); }); - describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function() { - it(`should update the sourcemap to account for manifest injection`, async function() { + describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function () { + it(`should update the sourcemap to account for manifest injection`, async function () { const outputDir = tempy.directory(); const swSrc = upath.join(SW_SRC_DIR, 'basic-with-sourcemap.js.nolint'); const swDest = upath.join(outputDir, 'basic-with-sourcemap.js'); - const sourcemapDest = upath.join(outputDir, 'basic-with-sourcemap.js.map'); + const sourcemapDest = upath.join( + outputDir, + 'basic-with-sourcemap.js.map', + ); const options = Object.assign({}, BASE_OPTIONS, { swDest, swSrc, @@ -377,20 +450,24 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); expect(filePaths).to.have.members([upath.resolve(swDest), sourcemapDest]); const actualSourcemap = await fse.readJSON(sourcemapDest); const expectedSourcemap = await fse.readJSON( - upath.join(SW_SRC_DIR, '..', 'expected-source-map.js.map')); + upath.join(SW_SRC_DIR, '..', 'expected-source-map.js.map'), + ); expect(actualSourcemap).to.eql(expectedSourcemap); // We can't validate the SW file contents. }); - it(`should not update the sourcemap if it uses a data: URL`, async function() { + it(`should not update the sourcemap if it uses a data: URL`, async function () { const outputDir = tempy.directory(); - const swSrc = upath.join(SW_SRC_DIR, 'basic-with-sourcemap-data-url.js.nolint'); + const swSrc = upath.join( + SW_SRC_DIR, + 'basic-with-sourcemap-data-url.js.nolint', + ); const swDest = upath.join(outputDir, 'basic-with-sourcemap.js'); const options = Object.assign({}, BASE_OPTIONS, { swDest, @@ -401,13 +478,13 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { expect(warnings).to.be.empty; expect(count).to.eql(6); // Line ending differences lead to different sizes on Windows. - expect(size).to.be.oneOf([2604, 2686]); + expect(size).to.be.oneOf([2782, 2698]); // We can't validate the SW file contents. }); }); - describe(`[workbox-build] removed options`, function() { + describe(`[workbox-build] removed options`, function () { // These were deprecated in v4, and formally removed in v5. const oldOptionsToValue = { dontCacheBustUrlsMatching: /ignored/, @@ -419,13 +496,15 @@ describe(`[workbox-build] inject-manifest.js (End to End)`, function() { }; for (const [option, value] of Object.entries(oldOptionsToValue)) { - it(`should fail validation when ${option} is used`, async function() { + it(`should fail validation when ${option} is used`, async function () { const options = Object.assign({}, BASE_OPTIONS, { [option]: value, }); await expect(injectManifest(options)).to.eventually.be.rejectedWith( - WorkboxConfigError, option); + WorkboxConfigError, + option, + ); }); } }); diff --git a/test/workbox-build/node/lib/additional-manifest-entries-transform.js b/test/workbox-build/node/lib/additional-manifest-entries-transform.js index 67d0a82c2..d492d0184 100644 --- a/test/workbox-build/node/lib/additional-manifest-entries-transform.js +++ b/test/workbox-build/node/lib/additional-manifest-entries-transform.js @@ -9,17 +9,21 @@ const expect = require('chai').expect; const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -const {additionalManifestEntriesTransform} = require('../../../../packages/workbox-build/build/lib/additional-manifest-entries-transform'); +const { + additionalManifestEntriesTransform, +} = require('../../../../packages/workbox-build/build/lib/additional-manifest-entries-transform'); -describe(`[workbox-build] lib/additional-manifest-entries-transform`, function() { +describe(`[workbox-build] lib/additional-manifest-entries-transform`, function () { function getManifest() { - return [{ - url: '/first', - revision: null, - }]; + return [ + { + url: '/first', + revision: null, + }, + ]; } - it(`should not make any changes when additionalManifestEntries is empty`, function() { + it(`should not make any changes when additionalManifestEntries is empty`, function () { const transform = additionalManifestEntriesTransform([]); expect(transform(getManifest())).to.eql({ manifest: [{url: '/first', revision: null}], @@ -27,7 +31,7 @@ describe(`[workbox-build] lib/additional-manifest-entries-transform`, function() }); }); - it(`should add the additionalManifestEntries to the end of the existing manifest`, function() { + it(`should add the additionalManifestEntries to the end of the existing manifest`, function () { const transform = additionalManifestEntriesTransform([ {url: '/second', revision: null}, {url: '/third', revision: null}, @@ -43,7 +47,7 @@ describe(`[workbox-build] lib/additional-manifest-entries-transform`, function() }); }); - it(`should return a warning, along with the modified manifest, when additionalManifestEntries contains a string or an entry without revision`, function() { + it(`should return a warning, along with the modified manifest, when additionalManifestEntries contains a string or an entry without revision`, function () { const transform = additionalManifestEntriesTransform([ '/second', {url: '/third'}, @@ -55,7 +59,9 @@ describe(`[workbox-build] lib/additional-manifest-entries-transform`, function() {url: '/second', size: 0, revision: null}, {url: '/third', size: 0}, ], - warnings: [errors['string-entry-warning'] + '\n - /second\n - /third\n'], + warnings: [ + errors['string-entry-warning'] + '\n - /second\n - /third\n', + ], }); }); }); diff --git a/test/workbox-build/node/lib/bundle.js b/test/workbox-build/node/lib/bundle.js index c30360de1..f62519a94 100644 --- a/test/workbox-build/node/lib/bundle.js +++ b/test/workbox-build/node/lib/bundle.js @@ -10,27 +10,33 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); const sinon = require('sinon'); -describe(`[workbox-build] lib/bundle`, function() { +describe(`[workbox-build] lib/bundle`, function () { const MODULE_PATH = '../../../../packages/workbox-build/build/lib/bundle'; let bundle; let stubs; - beforeEach(function() { + beforeEach(function () { const rollupStub = { - generate: sinon.stub().resolves({output: [{ - fileName: 'asset-filename', - type: 'asset', - source: 'asset-source', - }, { - code: 'chunk1-code', - fileName: 'chunk1-filename', - type: 'chunk', - }, { - code: 'chunk2-code', - fileName: 'chunk2-filename', - type: 'chunk', - map: 'sourcemap-contents', - }]}), + generate: sinon.stub().resolves({ + output: [ + { + fileName: 'asset-filename', + type: 'asset', + source: 'asset-source', + }, + { + code: 'chunk1-code', + fileName: 'chunk1-filename', + type: 'chunk', + }, + { + code: 'chunk2-code', + fileName: 'chunk2-filename', + type: 'chunk', + map: 'sourcemap-contents', + }, + ], + }), }; stubs = { @@ -63,7 +69,7 @@ describe(`[workbox-build] lib/bundle`, function() { bundle = proxyquire(MODULE_PATH, stubs).bundle; }); - it(`should pass 'babelPresetEnvTargets' to @babel/preset-env`, async function() { + it(`should pass 'babelPresetEnvTargets' to @babel/preset-env`, async function () { const babelPresetEnvTargets = ['target1', 'target2']; await bundle({ @@ -72,10 +78,12 @@ describe(`[workbox-build] lib/bundle`, function() { // This is ugly, but necessary due to the way babel() is configured. const babelParams = stubs['@rollup/plugin-babel'].babel.args[0][0]; - expect(babelParams.presets[0][1].targets.browsers).to.eql(babelPresetEnvTargets); + expect(babelParams.presets[0][1].targets.browsers).to.eql( + babelPresetEnvTargets, + ); }); - it(`should use loadz0r and configure manualChunks when 'inlineWorkboxRuntime' is false`, async function() { + it(`should use loadz0r and configure manualChunks when 'inlineWorkboxRuntime' is false`, async function () { await bundle({ inlineWorkboxRuntime: false, }); @@ -84,7 +92,7 @@ describe(`[workbox-build] lib/bundle`, function() { expect(stubs['@surma/rollup-plugin-off-main-thread'].calledOnce).to.be.true; }); - it(`should not use loadz0r or configure manualChunks when 'inlineWorkboxRuntime' is true`, async function() { + it(`should not use loadz0r or configure manualChunks when 'inlineWorkboxRuntime' is true`, async function () { await bundle({ inlineWorkboxRuntime: true, }); @@ -93,19 +101,23 @@ describe(`[workbox-build] lib/bundle`, function() { expect(stubs['@surma/rollup-plugin-off-main-thread'].notCalled).to.be.true; }); - it(`should replace NODE_ENV with the 'mode' value`, async function() { + it(`should replace NODE_ENV with the 'mode' value`, async function () { const mode = 'mode-value'; await bundle({ mode, }); - expect(stubs['@rollup/plugin-replace'].args).to.eql([[{ - 'preventAssignment': true, - 'process.env.NODE_ENV': `"${mode}"`, - }]]); + expect(stubs['@rollup/plugin-replace'].args).to.eql([ + [ + { + 'preventAssignment': true, + 'process.env.NODE_ENV': `"${mode}"`, + }, + ], + ]); }); - it(`should use terser when 'mode' is 'production'`, async function() { + it(`should use terser when 'mode' is 'production'`, async function () { const mode = 'production'; await bundle({ mode, @@ -114,7 +126,7 @@ describe(`[workbox-build] lib/bundle`, function() { expect(stubs['rollup-plugin-terser'].terser.calledOnce).to.be.true; }); - it(`should not use terser when 'mode' is not 'production'`, async function() { + it(`should not use terser when 'mode' is not 'production'`, async function () { const mode = 'something-else'; await bundle({ mode, @@ -123,7 +135,7 @@ describe(`[workbox-build] lib/bundle`, function() { expect(stubs['rollup-plugin-terser'].terser.notCalled).to.be.true; }); - it(`should pass the 'sourcemap' parameter value through to Rollup`, async function() { + it(`should pass the 'sourcemap' parameter value through to Rollup`, async function () { const sourcemap = true; await bundle({ sourcemap, @@ -132,21 +144,26 @@ describe(`[workbox-build] lib/bundle`, function() { expect(stubs.rollupStub.generate.args[0][0].sourcemap).to.eql(sourcemap); }); - it(`should process the generated Rollup bundle into the expected return value`, async function() { + it(`should process the generated Rollup bundle into the expected return value`, async function () { const files = await bundle({}); - expect(files).to.eql([{ - contents: 'asset-source', - name: 'asset-filename', - }, { - contents: 'chunk1-code', - name: 'chunk1-filename', - }, { - contents: 'sourcemap-contents', - name: 'chunk2-filename.map', - }, { - contents: 'chunk2-code//# sourceMappingURL=chunk2-filename.map\n', - name: 'chunk2-filename', - }]); + expect(files).to.eql([ + { + contents: 'asset-source', + name: 'asset-filename', + }, + { + contents: 'chunk1-code', + name: 'chunk1-filename', + }, + { + contents: 'sourcemap-contents', + name: 'chunk2-filename.map', + }, + { + contents: 'chunk2-code//# sourceMappingURL=chunk2-filename.map\n', + name: 'chunk2-filename', + }, + ]); }); }); diff --git a/test/workbox-build/node/lib/cdn-utils.js b/test/workbox-build/node/lib/cdn-utils.js index 706f2417c..d58f0a831 100644 --- a/test/workbox-build/node/lib/cdn-utils.js +++ b/test/workbox-build/node/lib/cdn-utils.js @@ -11,22 +11,20 @@ const expect = require('chai').expect; const cdnUtils = require('../../../../packages/workbox-build/build/lib/cdn-utils'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/cdn-utils.js`, function() { +describe(`[workbox-build] lib/cdn-utils.js`, function () { const CDN_ORIGIN = 'https://storage.googleapis.com/workbox-cdn/releases'; - it(`getModuleURL() should throw when moduleName is undefined`, function() { - expect( - () => cdnUtils.getModuleURL(), - ).to.throw(errors['no-module-name']); + it(`getModuleURL() should throw when moduleName is undefined`, function () { + expect(() => cdnUtils.getModuleURL()).to.throw(errors['no-module-name']); }); - it(`getModuleURL('workbox-sw', 'dev') should throw`, function() { - expect( - () => cdnUtils.getModuleURL('workbox-sw', 'dev'), - ).to.throw('workbox-sw'); + it(`getModuleURL('workbox-sw', 'dev') should throw`, function () { + expect(() => cdnUtils.getModuleURL('workbox-sw', 'dev')).to.throw( + 'workbox-sw', + ); }); - it(`getModuleURL(moduleName) should return the expected URL`, function() { + it(`getModuleURL(moduleName) should return the expected URL`, function () { const moduleName = 'workbox-sw'; const url = cdnUtils.getModuleURL(moduleName); @@ -34,7 +32,7 @@ describe(`[workbox-build] lib/cdn-utils.js`, function() { expect(url.includes(moduleName)).to.be.true; }); - it(`getModuleURL('workbox-routing', buildType) should return the expected URL`, function() { + it(`getModuleURL('workbox-routing', buildType) should return the expected URL`, function () { const moduleName = 'workbox-routing'; const buildType = 'prod'; diff --git a/test/workbox-build/node/lib/copy-workbox-libraries.js b/test/workbox-build/node/lib/copy-workbox-libraries.js index f1ab5051c..3eb680cf6 100644 --- a/test/workbox-build/node/lib/copy-workbox-libraries.js +++ b/test/workbox-build/node/lib/copy-workbox-libraries.js @@ -13,12 +13,13 @@ const sinon = require('sinon'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/copy-workbox-libraries.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/copy-workbox-libraries'; +describe(`[workbox-build] lib/copy-workbox-libraries.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/copy-workbox-libraries'; const ABSOLUTE_DEST_DIRECTORY = upath.join('/', 'test-dir'); const RELATIVE_DEST_DIRECTORY = upath.join('.', 'test-dir'); - it(`should reject with an error when the copy fails`, async function() { + it(`should reject with an error when the copy fails`, async function () { const {copyWorkboxLibraries} = proxyquire(MODULE_PATH, { 'fs-extra': { ensureDir: sinon.stub().resolves(), @@ -30,12 +31,14 @@ describe(`[workbox-build] lib/copy-workbox-libraries.js`, function() { await copyWorkboxLibraries(ABSOLUTE_DEST_DIRECTORY); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.have.string(errors['unable-to-copy-workbox-libraries']); + expect(error.message).to.have.string( + errors['unable-to-copy-workbox-libraries'], + ); } }); for (const destDir of [ABSOLUTE_DEST_DIRECTORY, RELATIVE_DEST_DIRECTORY]) { - it(`should resolve with the new directory name, using a destDir of ${destDir}`, async function() { + it(`should resolve with the new directory name, using a destDir of ${destDir}`, async function () { const copyStub = sinon.stub().resolves(); const ensureDirStub = sinon.stub().resolves(); diff --git a/test/workbox-build/node/lib/escape-regexp.js b/test/workbox-build/node/lib/escape-regexp.js index 1aa342573..03cab9aac 100644 --- a/test/workbox-build/node/lib/escape-regexp.js +++ b/test/workbox-build/node/lib/escape-regexp.js @@ -7,9 +7,11 @@ */ const expect = require('chai').expect; -const {escapeRegExp} = require('../../../../packages/workbox-build/build/lib/escape-regexp'); +const { + escapeRegExp, +} = require('../../../../packages/workbox-build/build/lib/escape-regexp'); -describe(`[workbox-build] lib/copy-workbox-libraries.js`, function() { +describe(`[workbox-build] lib/copy-workbox-libraries.js`, function () { const expectedValues = new Map([ ['abcd', 'abcd'], ['\\abc()d', '\\\\abc\\(\\)d'], @@ -18,7 +20,7 @@ describe(`[workbox-build] lib/copy-workbox-libraries.js`, function() { ]); for (const [original, escaped] of expectedValues) { - it(`should perform the expected escaping: ${original} => ${escaped}`, async function() { + it(`should perform the expected escaping: ${original} => ${escaped}`, async function () { expect(escapeRegExp(original)).to.eql(escaped); }); } diff --git a/test/workbox-build/node/lib/get-composite-details.js b/test/workbox-build/node/lib/get-composite-details.js index 71ea5360d..7ad9fd274 100644 --- a/test/workbox-build/node/lib/get-composite-details.js +++ b/test/workbox-build/node/lib/get-composite-details.js @@ -8,9 +8,11 @@ const expect = require('chai').expect; -const {getCompositeDetails} = require('../../../../packages/workbox-build/build/lib/get-composite-details'); +const { + getCompositeDetails, +} = require('../../../../packages/workbox-build/build/lib/get-composite-details'); -describe(`[workbox-build] lib/get-composite-details.js`, function() { +describe(`[workbox-build] lib/get-composite-details.js`, function () { const URL = '/test'; const ENTRY1 = { @@ -24,7 +26,7 @@ describe(`[workbox-build] lib/get-composite-details.js`, function() { hash: 'hash2', }; - it(`should return the expected composite details for a single file`, function() { + it(`should return the expected composite details for a single file`, function () { const details = getCompositeDetails(URL, [ENTRY1]); expect(details).to.eql({ file: URL, @@ -33,7 +35,7 @@ describe(`[workbox-build] lib/get-composite-details.js`, function() { }); }); - it(`should return the expected composite details for multiple files`, function() { + it(`should return the expected composite details for multiple files`, function () { const details = getCompositeDetails(URL, [ENTRY1, ENTRY2]); expect(details).to.eql({ file: URL, diff --git a/test/workbox-build/node/lib/get-file-details.js b/test/workbox-build/node/lib/get-file-details.js index 9cea809c6..e560ccdc4 100644 --- a/test/workbox-build/node/lib/get-file-details.js +++ b/test/workbox-build/node/lib/get-file-details.js @@ -12,8 +12,9 @@ const proxyquire = require('proxyquire'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/get-file-details.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/get-file-details'; +describe(`[workbox-build] lib/get-file-details.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/get-file-details'; const GLOB_DIRECTORY = './'; const GLOB_PATTERN = 'file*'; const DIRECTORY = 'directory'; @@ -22,7 +23,7 @@ describe(`[workbox-build] lib/get-file-details.js`, function() { const SIZE = 1234; const HASH = 'example-hash'; - it(`should throw when there's a glob.sync() error`, function() { + it(`should throw when there's a glob.sync() error`, function () { const {getFileDetails} = proxyquire(MODULE_PATH, { glob: { sync: () => { @@ -42,7 +43,7 @@ describe(`[workbox-build] lib/get-file-details.js`, function() { } }); - it(`should return a warning when the pattern doesn't match anything`, function() { + it(`should return a warning when the pattern doesn't match anything`, function () { const {getFileDetails} = proxyquire(MODULE_PATH, { glob: { sync: () => [], @@ -57,7 +58,7 @@ describe(`[workbox-build] lib/get-file-details.js`, function() { expect(warning).to.have.string(errors['useless-glob-pattern']); }); - it(`should return array of file details, without null values`, function() { + it(`should return array of file details, without null values`, function () { const {getFileDetails} = proxyquire(MODULE_PATH, { 'glob': { sync: () => { @@ -75,7 +76,9 @@ describe(`[workbox-build] lib/get-file-details.js`, function() { './get-file-hash': { getFileHash: (value) => { if (upath.normalize(value) === upath.normalize(DIRECTORY)) { - throw new Error(`getFileHash(${DIRECTORY}) shouldn't have been called.`); + throw new Error( + `getFileHash(${DIRECTORY}) shouldn't have been called.`, + ); } return HASH; }, @@ -88,14 +91,17 @@ describe(`[workbox-build] lib/get-file-details.js`, function() { }); expect(warning).to.eql(''); - expect(globbedFileDetails).to.deep.equal([{ - file: FILE1, - hash: HASH, - size: SIZE, - }, { - file: FILE2, - hash: HASH, - size: SIZE, - }]); + expect(globbedFileDetails).to.deep.equal([ + { + file: FILE1, + hash: HASH, + size: SIZE, + }, + { + file: FILE2, + hash: HASH, + size: SIZE, + }, + ]); }); }); diff --git a/test/workbox-build/node/lib/get-file-hash.js b/test/workbox-build/node/lib/get-file-hash.js index d5954ba55..bc7a9b5eb 100644 --- a/test/workbox-build/node/lib/get-file-hash.js +++ b/test/workbox-build/node/lib/get-file-hash.js @@ -11,11 +11,12 @@ const proxyquire = require('proxyquire'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/get-file-hash.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/get-file-hash'; +describe(`[workbox-build] lib/get-file-hash.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/get-file-hash'; const FILE = 'file.txt'; - it(`should throw when there's a fs.readFileSync() error`, function() { + it(`should throw when there's a fs.readFileSync() error`, function () { const {getFileHash} = proxyquire(MODULE_PATH, { 'fs-extra': { readFileSync: () => { @@ -32,7 +33,7 @@ describe(`[workbox-build] lib/get-file-hash.js`, function() { } }); - it(`should return the hash corresponding to a file's contents`, function() { + it(`should return the hash corresponding to a file's contents`, function () { const buffer = Buffer.alloc(10); const hashForBuffer = 'a63c90cc3684ad8b0a2176a6a8fe9005'; diff --git a/test/workbox-build/node/lib/get-file-manifest-entries.js b/test/workbox-build/node/lib/get-file-manifest-entries.js index bc04b7bc8..77ccd0669 100644 --- a/test/workbox-build/node/lib/get-file-manifest-entries.js +++ b/test/workbox-build/node/lib/get-file-manifest-entries.js @@ -11,8 +11,9 @@ const proxyquire = require('proxyquire'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] Test getFileManifestEntries`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/get-file-manifest-entries'; +describe(`[workbox-build] Test getFileManifestEntries`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/get-file-manifest-entries'; const GLOB_DIRECTORY = './'; const GLOB_PATTERNS = ['invalid*']; const FILE = { @@ -21,7 +22,7 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { hash: 'hash1', }; - it(`should return empty info when neither globDirectory nor templatedURLs are provided`, async function() { + it(`should return empty info when neither globDirectory nor templatedURLs are provided`, async function () { const {getFileManifestEntries} = require(MODULE_PATH); const {count, size, manifestEntries} = await getFileManifestEntries({}); @@ -31,7 +32,7 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { expect(manifestEntries).to.have.lengthOf(0); }); - it(`should not return the same file twice`, async function() { + it(`should not return the same file twice`, async function () { const {getFileManifestEntries} = proxyquire(MODULE_PATH, { './get-file-details': { getFileDetails: () => { @@ -50,13 +51,15 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { expect(count).to.eql(1); expect(size).to.eql(FILE.size); - expect(manifestEntries).to.deep.equal([{ - url: FILE.file, - revision: FILE.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: FILE.file, + revision: FILE.hash, + }, + ]); }); - it(`should throw when a templatedURL matches a globbed file`, async function() { + it(`should throw when a templatedURL matches a globbed file`, async function () { const {getFileManifestEntries} = proxyquire(MODULE_PATH, { './get-file-details': { getFileDetails: () => { @@ -78,11 +81,13 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { }); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.have.string(errors['templated-url-matches-glob']); + expect(error.message).to.have.string( + errors['templated-url-matches-glob'], + ); } }); - it(`should treat an exception thrown by getFileDetails() as a warning message`, async function() { + it(`should treat an exception thrown by getFileDetails() as a warning message`, async function () { const warningMessage = 'test warning'; const {getFileManifestEntries} = proxyquire(MODULE_PATH, { './get-file-details': { @@ -103,7 +108,7 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { expect(warnings).to.eql([warningMessage]); }); - it(`should throw when a templatedURL contains a pattern that doesn't match anything`, async function() { + it(`should throw when a templatedURL contains a pattern that doesn't match anything`, async function () { const {getFileManifestEntries} = require(MODULE_PATH); try { @@ -119,7 +124,7 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { } }); - it(`should return results that take both glob patterns and templatedURLs into account`, async function() { + it(`should return results that take both glob patterns and templatedURLs into account`, async function () { const url1 = '/path/to/url1'; const url2 = '/path/to/url2'; const stringValue = 'string'; @@ -146,17 +151,21 @@ describe(`[workbox-build] Test getFileManifestEntries`, function() { expect(count).to.eql(3); expect(size).to.eql(FILE.size + FILE.size + stringValue.length); - expect(manifestEntries).to.deep.equal([{ - url: FILE.file, - revision: FILE.hash, - }, { - url: url1, - // This is the hash of FILE.hash. - revision: '00c6ee2e21a7548de6260cf72c4f4b5b', - }, { - url: url2, - // THis is the hash of stringValue. - revision: 'b45cffe084dd3d20d928bee85e7b0f21', - }]); + expect(manifestEntries).to.deep.equal([ + { + url: FILE.file, + revision: FILE.hash, + }, + { + url: url1, + // This is the hash of FILE.hash. + revision: '00c6ee2e21a7548de6260cf72c4f4b5b', + }, + { + url: url2, + // THis is the hash of stringValue. + revision: 'b45cffe084dd3d20d928bee85e7b0f21', + }, + ]); }); }); diff --git a/test/workbox-build/node/lib/get-file-size.js b/test/workbox-build/node/lib/get-file-size.js index b1b7ef490..9c4f4cbb5 100644 --- a/test/workbox-build/node/lib/get-file-size.js +++ b/test/workbox-build/node/lib/get-file-size.js @@ -9,13 +9,16 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../packages/workbox-build/build/lib/errors.js'); +const { + errors, +} = require('../../../../packages/workbox-build/build/lib/errors.js'); -describe(`[workbox-build] lib/get-file-size.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/get-file-size'; +describe(`[workbox-build] lib/get-file-size.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/get-file-size'; const FILE = 'file.txt'; - it(`should throw when fs.statSync() fails`, function() { + it(`should throw when fs.statSync() fails`, function () { const {getFileSize} = proxyquire(MODULE_PATH, { 'fs-extra': { statSync: () => { @@ -32,7 +35,7 @@ describe(`[workbox-build] lib/get-file-size.js`, function() { } }); - it(`should return null for non-files`, function() { + it(`should return null for non-files`, function () { const {getFileSize} = proxyquire(MODULE_PATH, { 'fs-extra': { statSync: () => { @@ -47,7 +50,7 @@ describe(`[workbox-build] lib/get-file-size.js`, function() { expect(size).not.to.exist; }); - it(`should return the expected file size`, function() { + it(`should return the expected file size`, function () { const expectedSize = 1234; const {getFileSize} = proxyquire(MODULE_PATH, { diff --git a/test/workbox-build/node/lib/get-string-details.js b/test/workbox-build/node/lib/get-string-details.js index 6e0d326cc..1b6013996 100644 --- a/test/workbox-build/node/lib/get-string-details.js +++ b/test/workbox-build/node/lib/get-string-details.js @@ -8,21 +8,29 @@ const expect = require('chai').expect; -const {getStringDetails} = require('../../../../packages/workbox-build/build/lib/get-string-details'); +const { + getStringDetails, +} = require('../../../../packages/workbox-build/build/lib/get-string-details'); -describe(`[workbox-build] lib/get-string-details.js`, function() { - it(`should return the expected details`, function() { +describe(`[workbox-build] lib/get-string-details.js`, function () { + it(`should return the expected details`, function () { const inputToExpectedDetails = new Map([ - [['/url-one', 'first-one'], { - file: '/url-one', - hash: 'e725107146e32e2e7e75feaa303b7fbc', - size: 9, - }], - [['/url-two', 'another-string'], { - file: '/url-two', - hash: '7fb80c5fad3565fd6ce3d9f61a53c659', - size: 14, - }], + [ + ['/url-one', 'first-one'], + { + file: '/url-one', + hash: 'e725107146e32e2e7e75feaa303b7fbc', + size: 9, + }, + ], + [ + ['/url-two', 'another-string'], + { + file: '/url-two', + hash: '7fb80c5fad3565fd6ce3d9f61a53c659', + size: 14, + }, + ], ]); for (const [[url, string], expectedDetails] of inputToExpectedDetails) { diff --git a/test/workbox-build/node/lib/get-string-hash.js b/test/workbox-build/node/lib/get-string-hash.js index 7c4826235..6ac23461f 100644 --- a/test/workbox-build/node/lib/get-string-hash.js +++ b/test/workbox-build/node/lib/get-string-hash.js @@ -8,10 +8,12 @@ const expect = require('chai').expect; -const {getStringHash} = require('../../../../packages/workbox-build/build/lib/get-string-hash'); +const { + getStringHash, +} = require('../../../../packages/workbox-build/build/lib/get-string-hash'); -describe(`[workbox-build] lib/get-string-hash.js`, function() { - it(`should return the expected hashes`, function() { +describe(`[workbox-build] lib/get-string-hash.js`, function () { + it(`should return the expected hashes`, function () { const stringsToHashes = new Map([ ['abc', '900150983cd24fb0d6963f7d28e17f72'], ['xyz', 'd16fb36f0911f878998c136191af705e'], diff --git a/test/workbox-build/node/lib/modify-url-prefix-transform.js b/test/workbox-build/node/lib/modify-url-prefix-transform.js index 068f11406..7af5788a3 100644 --- a/test/workbox-build/node/lib/modify-url-prefix-transform.js +++ b/test/workbox-build/node/lib/modify-url-prefix-transform.js @@ -9,26 +9,24 @@ const expect = require('chai').expect; const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -const {modifyURLPrefixTransform} = require('../../../../packages/workbox-build/build/lib/modify-url-prefix-transform'); +const { + modifyURLPrefixTransform, +} = require('../../../../packages/workbox-build/build/lib/modify-url-prefix-transform'); -describe(`[workbox-build] lib/modify-url-prefix-transform.js`, function() { +describe(`[workbox-build] lib/modify-url-prefix-transform.js`, function () { function getManifest() { - return [{ - url: '/first-match/12345/hello', - }, { - url: '/second-match/12345/hello', - }]; + return [ + { + url: '/first-match/12345/hello', + }, + { + url: '/second-match/12345/hello', + }, + ]; } - it(`should handle bad URLs in the manifest`, function() { - const badInputs = [ - null, - undefined, - true, - false, - {}, - [], - ]; + it(`should handle bad URLs in the manifest`, function () { + const badInputs = [null, undefined, true, false, {}, []]; const modifications = { '/example-1': '/example-1-altered', @@ -37,13 +35,13 @@ describe(`[workbox-build] lib/modify-url-prefix-transform.js`, function() { const transform = modifyURLPrefixTransform(modifications); for (const badInput of badInputs) { - expect( - () => transform([{url: badInput}]), - ).to.throw(errors['manifest-entry-bad-url']); + expect(() => transform([{url: badInput}])).to.throw( + errors['manifest-entry-bad-url'], + ); } }); - it(`should handle bad modifyURLPrefixTransform input`, function() { + it(`should handle bad modifyURLPrefixTransform input`, function () { const badInputs = [ null, undefined, @@ -52,58 +50,73 @@ describe(`[workbox-build] lib/modify-url-prefix-transform.js`, function() { [], '', { - 'Hi': [], + Hi: [], }, ]; for (const badInput of badInputs) { - expect( - () => modifyURLPrefixTransform(badInput), - ).to.throw(errors['modify-url-prefix-bad-prefixes']); + expect(() => modifyURLPrefixTransform(badInput)).to.throw( + errors['modify-url-prefix-bad-prefixes'], + ); } }); - it(`should strip prefixes`, function() { + it(`should strip prefixes`, function () { const modifications = { '/first-match': '', }; const transform = modifyURLPrefixTransform(modifications); - expect(transform(getManifest())).to.eql({manifest: [{ - url: '/12345/hello', - }, { - url: '/second-match/12345/hello', - }]}); + expect(transform(getManifest())).to.eql({ + manifest: [ + { + url: '/12345/hello', + }, + { + url: '/second-match/12345/hello', + }, + ], + }); }); - it(`should prepend prefixes`, function() { + it(`should prepend prefixes`, function () { const modifications = { '': '/public', }; const transform = modifyURLPrefixTransform(modifications); - expect(transform(getManifest())).to.eql({manifest: [{ - url: '/public/first-match/12345/hello', - }, { - url: '/public/second-match/12345/hello', - }]}); + expect(transform(getManifest())).to.eql({ + manifest: [ + { + url: '/public/first-match/12345/hello', + }, + { + url: '/public/second-match/12345/hello', + }, + ], + }); }); - it(`should only replace the initial match`, function() { + it(`should only replace the initial match`, function () { const modifications = { '/first-match': '/second-match', '/second-match': '/third-match', }; const transform = modifyURLPrefixTransform(modifications); - expect(transform(getManifest())).to.eql({manifest: [{ - url: '/second-match/12345/hello', - }, { - url: '/third-match/12345/hello', - }]}); + expect(transform(getManifest())).to.eql({ + manifest: [ + { + url: '/second-match/12345/hello', + }, + { + url: '/third-match/12345/hello', + }, + ], + }); }); - it(`should not replace when the match is not at the start of the URL`, function() { + it(`should not replace when the match is not at the start of the URL`, function () { const modifications = { '/hello': '/altered', }; diff --git a/test/workbox-build/node/lib/module-registry.js b/test/workbox-build/node/lib/module-registry.js index 0a665515d..6227720d1 100644 --- a/test/workbox-build/node/lib/module-registry.js +++ b/test/workbox-build/node/lib/module-registry.js @@ -9,9 +9,11 @@ const expect = require('chai').expect; const upath = require('upath'); -const {ModuleRegistry} = require('../../../../packages/workbox-build/build/lib/module-registry'); +const { + ModuleRegistry, +} = require('../../../../packages/workbox-build/build/lib/module-registry'); -describe(`[workbox-build] lib/module-registry.js`, function() { +describe(`[workbox-build] lib/module-registry.js`, function () { let moduleRegistry; // We can't use proxyquire to override require.resolve(), so let's get the // actual expected base path that will be used in the test cases. @@ -21,12 +23,12 @@ describe(`[workbox-build] lib/module-registry.js`, function() { moduleRegistry = new ModuleRegistry(); }); - describe(`getImportStatements()`, function() { - it(`should return [] when nothing is used`, function() { + describe(`getImportStatements()`, function () { + it(`should return [] when nothing is used`, function () { expect(moduleRegistry.getImportStatements()).to.be.empty; }); - it(`return the expected output given multiple calls to use()`, function() { + it(`return the expected output given multiple calls to use()`, function () { const module1Name = moduleRegistry.use('workbox-core', 'index'); // Multiple use()s should result in only one entry. moduleRegistry.use('workbox-core', 'index'); @@ -44,12 +46,12 @@ describe(`[workbox-build] lib/module-registry.js`, function() { }); }); - describe(`getLocalName()`, function() { - it(`should return the expected name`, function() { + describe(`getLocalName()`, function () { + it(`should return the expected name`, function () { expect(moduleRegistry.getLocalName('a-b-c', 'd')).to.eql('a_b_c_d'); }); - it(`should return the expected name when called via use()`, function() { + it(`should return the expected name when called via use()`, function () { expect(moduleRegistry.use('a-b-c', 'd')).to.eql('a_b_c_d'); }); }); diff --git a/test/workbox-build/node/lib/no-revision-for-urls-matching-transform.js b/test/workbox-build/node/lib/no-revision-for-urls-matching-transform.js index a536000ff..c0875ef6f 100644 --- a/test/workbox-build/node/lib/no-revision-for-urls-matching-transform.js +++ b/test/workbox-build/node/lib/no-revision-for-urls-matching-transform.js @@ -9,38 +9,37 @@ const expect = require('chai').expect; const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -const {noRevisionForURLsMatchingTransform} = require('../../../../packages/workbox-build/build/lib/no-revision-for-urls-matching-transform'); +const { + noRevisionForURLsMatchingTransform, +} = require('../../../../packages/workbox-build/build/lib/no-revision-for-urls-matching-transform'); -describe(`[workbox-build] lib/no-revision-for-urls-matching-transform.js`, function() { - const MANIFEST = [{ - url: '/first-match/12345/hello', - revision: '1234abcd', - }, { - url: '/second-match/12345/hello', - revision: '1234abcd', - }, { - url: '/third-match/12345/hello', - }]; +describe(`[workbox-build] lib/no-revision-for-urls-matching-transform.js`, function () { + const MANIFEST = [ + { + url: '/first-match/12345/hello', + revision: '1234abcd', + }, + { + url: '/second-match/12345/hello', + revision: '1234abcd', + }, + { + url: '/third-match/12345/hello', + }, + ]; - it(`should handle bad URLs in the manifest`, function() { - const badInputs = [ - null, - undefined, - true, - false, - {}, - [], - ]; + it(`should handle bad URLs in the manifest`, function () { + const badInputs = [null, undefined, true, false, {}, []]; const transform = noRevisionForURLsMatchingTransform(/ignored/); for (const badInput of badInputs) { - expect( - () => transform([{url: badInput}]), - ).to.throw(errors['manifest-entry-bad-url']); + expect(() => transform([{url: badInput}])).to.throw( + errors['manifest-entry-bad-url'], + ); } }); - it(`should handle bad dontCacheBustURLsMatching input`, function() { + it(`should handle bad dontCacheBustURLsMatching input`, function () { const badInputs = [ null, undefined, @@ -49,45 +48,57 @@ describe(`[workbox-build] lib/no-revision-for-urls-matching-transform.js`, funct [], '', { - 'Hi': [], + Hi: [], }, ]; for (const badInput of badInputs) { - expect( - () => noRevisionForURLsMatchingTransform(badInput), - ).to.throw(errors['invalid-dont-cache-bust']); + expect(() => noRevisionForURLsMatchingTransform(badInput)).to.throw( + errors['invalid-dont-cache-bust'], + ); } }); - it(`should set revision info to null in a single matching entry`, function() { + it(`should set revision info to null in a single matching entry`, function () { const transform = noRevisionForURLsMatchingTransform(/first-match/); - expect(transform(MANIFEST)).to.eql({manifest: [{ - url: '/first-match/12345/hello', - revision: null, - }, { - url: '/second-match/12345/hello', - revision: '1234abcd', - }, { - url: '/third-match/12345/hello', - }]}); + expect(transform(MANIFEST)).to.eql({ + manifest: [ + { + url: '/first-match/12345/hello', + revision: null, + }, + { + url: '/second-match/12345/hello', + revision: '1234abcd', + }, + { + url: '/third-match/12345/hello', + }, + ], + }); }); - it(`should set revision info to null in multiple matching entries`, function() { + it(`should set revision info to null in multiple matching entries`, function () { const transform = noRevisionForURLsMatchingTransform(/12345/); - expect(transform(MANIFEST)).to.eql({manifest: [{ - url: '/first-match/12345/hello', - revision: null, - }, { - url: '/second-match/12345/hello', - revision: null, - }, { - url: '/third-match/12345/hello', - revision: null, - }]}); + expect(transform(MANIFEST)).to.eql({ + manifest: [ + { + url: '/first-match/12345/hello', + revision: null, + }, + { + url: '/second-match/12345/hello', + revision: null, + }, + { + url: '/third-match/12345/hello', + revision: null, + }, + ], + }); }); - it(`should do nothing when there's a match for an entry without a revision`, function() { + it(`should do nothing when there's a match for an entry without a revision`, function () { const transform = noRevisionForURLsMatchingTransform(/third-match/); expect(transform(MANIFEST)).to.eql({manifest: MANIFEST}); }); diff --git a/test/workbox-build/node/lib/populate-sw-template.js b/test/workbox-build/node/lib/populate-sw-template.js index b64f877e3..3d5e88b7c 100644 --- a/test/workbox-build/node/lib/populate-sw-template.js +++ b/test/workbox-build/node/lib/populate-sw-template.js @@ -12,10 +12,11 @@ const sinon = require('sinon'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/populate-sw-template.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/populate-sw-template'; +describe(`[workbox-build] lib/populate-sw-template.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/populate-sw-template'; - it(`should throw an error if templating fails`, function() { + it(`should throw an error if templating fails`, function () { const manifestEntries = ['ignored']; const {populateSWTemplate} = proxyquire(MODULE_PATH, { @@ -32,7 +33,7 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { } }); - it(`should throw an error if both manifestEntries and runtimeCaching are empty`, function() { + it(`should throw an error if both manifestEntries and runtimeCaching are empty`, function () { const {populateSWTemplate} = proxyquire(MODULE_PATH, { 'lodash/template': () => {}, }); @@ -41,11 +42,13 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { populateSWTemplate({manifestEntries: [], runtimeCaching: []}); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.have.string(errors['no-manifest-entries-or-runtime-caching']); + expect(error.message).to.have.string( + errors['no-manifest-entries-or-runtime-caching'], + ); } }); - it(`should pass the expected options to the template using mostly defaults`, function() { + it(`should pass the expected options to the template using mostly defaults`, function () { const runtimeCachingPlaceholder = 'runtime-caching-placeholder'; const swTemplate = 'template'; const precacheOptionsString = '{}'; @@ -67,27 +70,29 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { // Doing a strict comparison with functions isn't easy. expect(innerStub.args[0][0].use).to.be.a('function'); - delete(innerStub.args[0][0].use); - - expect(innerStub.args[0]).to.eql([{ - manifestEntries, - cacheId: undefined, - cleanupOutdatedCaches: undefined, - clientsClaim: undefined, - disableDevLogs: undefined, - importScripts: undefined, - navigateFallback: undefined, - navigateFallbackDenylist: undefined, - navigateFallbackAllowlist: undefined, - navigationPreload: undefined, - offlineAnalyticsConfigString: undefined, - precacheOptionsString, - runtimeCaching: runtimeCachingPlaceholder, - skipWaiting: undefined, - }]); + delete innerStub.args[0][0].use; + + expect(innerStub.args[0]).to.eql([ + { + manifestEntries, + cacheId: undefined, + cleanupOutdatedCaches: undefined, + clientsClaim: undefined, + disableDevLogs: undefined, + importScripts: undefined, + navigateFallback: undefined, + navigateFallbackDenylist: undefined, + navigateFallbackAllowlist: undefined, + navigationPreload: undefined, + offlineAnalyticsConfigString: undefined, + precacheOptionsString, + runtimeCaching: runtimeCachingPlaceholder, + skipWaiting: undefined, + }, + ]); }); - it(`should pass the expected options to the template`, function() { + it(`should pass the expected options to the template`, function () { const cacheId = 'test-cache-id'; const cleanupOutdatedCaches = true; const clientsClaim = true; @@ -107,7 +112,8 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { const runtimeCachingPlaceholder = 'runtime-caching-placeholder'; const skipWaiting = true; const swTemplate = 'template'; - const precacheOptionsString = '{\n "directoryIndex": "index.html",\n "ignoreURLParametersMatching": [/a/, /b/]\n}'; + const precacheOptionsString = + '{\n "directoryIndex": "index.html",\n "ignoreURLParametersMatching": [/a/, /b/]\n}'; // There are two stages in templating: creating the active template function // from an initial string, and passing variables to that template function @@ -146,27 +152,29 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { // Doing a strict comparison with functions isn't easy. expect(templatePopulationStub.args[0][0].use).to.be.a('function'); - delete(templatePopulationStub.args[0][0].use); - - expect(templatePopulationStub.args[0]).to.eql([{ - cacheId, - cleanupOutdatedCaches, - clientsClaim, - disableDevLogs, - importScripts, - manifestEntries, - navigateFallback, - navigateFallbackDenylist, - navigateFallbackAllowlist, - navigationPreload, - offlineAnalyticsConfigString, - runtimeCaching: runtimeCachingPlaceholder, - precacheOptionsString, - skipWaiting, - }]); + delete templatePopulationStub.args[0][0].use; + + expect(templatePopulationStub.args[0]).to.eql([ + { + cacheId, + cleanupOutdatedCaches, + clientsClaim, + disableDevLogs, + importScripts, + manifestEntries, + navigateFallback, + navigateFallbackDenylist, + navigateFallbackAllowlist, + navigationPreload, + offlineAnalyticsConfigString, + runtimeCaching: runtimeCachingPlaceholder, + precacheOptionsString, + skipWaiting, + }, + ]); }); - it(`should handle a complex offlineGoogleAnalytics value when populating the template`, function() { + it(`should handle a complex offlineGoogleAnalytics value when populating the template`, function () { const runtimeCachingPlaceholder = 'runtime-caching-placeholder'; const swTemplate = 'template'; const precacheOptionsString = '{}'; @@ -198,23 +206,25 @@ describe(`[workbox-build] lib/populate-sw-template.js`, function() { // Doing a strict comparison with functions isn't easy. expect(innerStub.args[0][0].use).to.be.a('function'); - delete(innerStub.args[0][0].use); - - expect(innerStub.args[0]).to.eql([{ - manifestEntries, - cacheId: undefined, - cleanupOutdatedCaches: undefined, - clientsClaim: undefined, - disableDevLogs: undefined, - importScripts: undefined, - navigateFallback: undefined, - navigateFallbackDenylist: undefined, - navigateFallbackAllowlist: undefined, - navigationPreload: undefined, - offlineAnalyticsConfigString, - precacheOptionsString, - runtimeCaching: runtimeCachingPlaceholder, - skipWaiting: undefined, - }]); + delete innerStub.args[0][0].use; + + expect(innerStub.args[0]).to.eql([ + { + manifestEntries, + cacheId: undefined, + cleanupOutdatedCaches: undefined, + clientsClaim: undefined, + disableDevLogs: undefined, + importScripts: undefined, + navigateFallback: undefined, + navigateFallbackDenylist: undefined, + navigateFallbackAllowlist: undefined, + navigationPreload: undefined, + offlineAnalyticsConfigString, + precacheOptionsString, + runtimeCaching: runtimeCachingPlaceholder, + skipWaiting: undefined, + }, + ]); }); }); diff --git a/test/workbox-build/node/lib/replace-and-update-source-map.js b/test/workbox-build/node/lib/replace-and-update-source-map.js index 4cbcf451b..e347f7a06 100644 --- a/test/workbox-build/node/lib/replace-and-update-source-map.js +++ b/test/workbox-build/node/lib/replace-and-update-source-map.js @@ -8,9 +8,11 @@ const expect = require('chai').expect; -const {replaceAndUpdateSourceMap} = require('../../../../packages/workbox-build/build/lib/replace-and-update-source-map'); +const { + replaceAndUpdateSourceMap, +} = require('../../../../packages/workbox-build/build/lib/replace-and-update-source-map'); -describe(`[workbox-build] lib/replace-and-update-source-map`, function() { +describe(`[workbox-build] lib/replace-and-update-source-map`, function () { // Test case borrowed from https://github.com/Rich-Harris/magic-string/blob/a312519cfe9caa78ade7f09cc2b07459d3d17f4d/test/MagicString.js#L225 const JS_FILENAME = 'file.js'; const SOURCE = `abcdefkl`; @@ -24,7 +26,7 @@ describe(`[workbox-build] lib/replace-and-update-source-map`, function() { version: 3, }; - it(`should be a no-op if there's no match`, async function() { + it(`should be a no-op if there's no match`, async function () { const {map, source} = await replaceAndUpdateSourceMap({ jsFilename: JS_FILENAME, originalSource: SOURCE, @@ -37,7 +39,7 @@ describe(`[workbox-build] lib/replace-and-update-source-map`, function() { expect(source).to.eql(SOURCE); }); - it(`should be perform the replacement and update the sourcemap when there is a match`, async function() { + it(`should be perform the replacement and update the sourcemap when there is a match`, async function () { const searchString = 'bc'; const replaceString = 'wxyz'; diff --git a/test/workbox-build/node/lib/runtime-caching-converter.js b/test/workbox-build/node/lib/runtime-caching-converter.js index 49f88be7a..81b1b4fa5 100644 --- a/test/workbox-build/node/lib/runtime-caching-converter.js +++ b/test/workbox-build/node/lib/runtime-caching-converter.js @@ -11,8 +11,12 @@ const sinon = require('sinon'); const vm = require('vm'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -const {ModuleRegistry} = require('../../../../packages/workbox-build/build/lib/module-registry'); -const {runtimeCachingConverter} = require('../../../../packages/workbox-build/build/lib/runtime-caching-converter'); +const { + ModuleRegistry, +} = require('../../../../packages/workbox-build/build/lib/module-registry'); +const { + runtimeCachingConverter, +} = require('../../../../packages/workbox-build/build/lib/runtime-caching-converter'); const moduleRegistry = new ModuleRegistry(); @@ -53,7 +57,8 @@ function validate(runtimeCachingOptions, convertedOptions) { const script = new vm.Script(convertedOptions.join('\n')); script.runInNewContext(globalScope); runtimeCachingOptions.forEach((runtimeCachingOption, i) => { - const registerRouteCall = globalScope.workbox_routing_registerRoute.getCall(i); + const registerRouteCall = + globalScope.workbox_routing_registerRoute.getCall(i); expect(registerRouteCall.args[0]).to.eql(runtimeCachingOption.urlPattern); if (runtimeCachingOption.method) { @@ -69,14 +74,16 @@ function validate(runtimeCachingOptions, convertedOptions) { // This validation assumes that there's only going to be one call to each // named strategy per test. - const strategiesCall = handlerMapping[runtimeCachingOption.handler].firstCall; + const strategiesCall = + handlerMapping[runtimeCachingOption.handler].firstCall; const strategiesOptions = strategiesCall.args[0]; if (runtimeCachingOption.options) { const options = runtimeCachingOption.options; if (options.networkTimeoutSeconds) { - expect(options.networkTimeoutSeconds) - .to.eql(strategiesOptions.networkTimeoutSeconds); + expect(options.networkTimeoutSeconds).to.eql( + strategiesOptions.networkTimeoutSeconds, + ); } if (options.cacheName) { @@ -84,39 +91,60 @@ function validate(runtimeCachingOptions, convertedOptions) { } if (options.fetchOptions) { - expect(options.fetchOptions).to.deep.eql(strategiesOptions.fetchOptions); + expect(options.fetchOptions).to.deep.eql( + strategiesOptions.fetchOptions, + ); } if (options.matchOptions) { - expect(options.matchOptions).to.deep.eql(strategiesOptions.matchOptions); + expect(options.matchOptions).to.deep.eql( + strategiesOptions.matchOptions, + ); } if (Object.keys(options.expiration).length > 0) { - expect(globalScope.workbox_expiration_ExpirationPlugin.calledWith(options.expiration)).to.be.true; + expect( + globalScope.workbox_expiration_ExpirationPlugin.calledWith( + options.expiration, + ), + ).to.be.true; } if (options.cacheableResponse) { - expect(globalScope.workbox_cacheable_response_CacheableResponsePlugin.calledWith(options.cacheableResponse)).to.be.true; + expect( + globalScope.workbox_cacheable_response_CacheableResponsePlugin.calledWith( + options.cacheableResponse, + ), + ).to.be.true; } if (options.precacheFallback) { - expect(globalScope.workbox_precaching_PrecacheFallbackPlugin.calledWith(options.precacheFallback)).to.be.true; + expect( + globalScope.workbox_precaching_PrecacheFallbackPlugin.calledWith( + options.precacheFallback, + ), + ).to.be.true; } if (options.rangeRequests) { - expect(globalScope.workbox_range_requests_RangeRequestsPlugin.calledWith()).to.be.true; + expect( + globalScope.workbox_range_requests_RangeRequestsPlugin.calledWith(), + ).to.be.true; } if (options.backgroundSync) { if ('options' in options.backgroundSync) { expect( - globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( - options.backgroundSync.name, options.backgroundSync.options), + globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( + options.backgroundSync.name, + options.backgroundSync.options, + ), ).to.be.true; } else { expect( - globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( - options.backgroundSync.name), + globalScope.workbox_background_sync_BackgroundSyncPlugin.calledWith( + options.backgroundSync.name, + ), ).to.be.true; } } @@ -124,223 +152,300 @@ function validate(runtimeCachingOptions, convertedOptions) { if (options.broadcastUpdate) { if ('options' in options.broadcastUpdate) { const expectedOptions = Object.assign( - {channelName: options.broadcastUpdate.channelName}, - options.broadcastUpdate.options); - expect(globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith(expectedOptions)) - .to.be.true; + {channelName: options.broadcastUpdate.channelName}, + options.broadcastUpdate.options, + ); + expect( + globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith( + expectedOptions, + ), + ).to.be.true; } else { - expect(globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith( - {channelName: options.broadcastUpdate.channelName})).to.be.true; + expect( + globalScope.workbox_broadcast_update_BroadcastUpdatePlugin.calledWith( + {channelName: options.broadcastUpdate.channelName}, + ), + ).to.be.true; } } } }); } -describe(`[workbox-build] src/lib/utils/runtime-caching-converter.js`, function() { - it(`should throw when urlPattern isn't set`, function() { - const runtimeCachingOptions = [{ - handler: 'CacheFirst', - }]; +describe(`[workbox-build] src/lib/utils/runtime-caching-converter.js`, function () { + it(`should throw when urlPattern isn't set`, function () { + const runtimeCachingOptions = [ + { + handler: 'CacheFirst', + }, + ]; expect(() => { runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); }).to.throw(errors['urlPattern-is-required']); }); - it(`should throw when handler isn't set`, function() { - const runtimeCachingOptions = [{ - urlPattern: /xyz/, - }]; + it(`should throw when handler isn't set`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /xyz/, + }, + ]; expect(() => { runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); }).to.throw(errors['handler-string-is-required']); }); - it(`should support an empty array of runtimeCaching options`, function() { + it(`should support an empty array of runtimeCaching options`, function () { const runtimeCachingOptions = []; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); - it(`should support a single option with a RegExp urlPattern, using mostly defaults`, function() { - const runtimeCachingOptions = [{ - urlPattern: /xyz/, - handler: 'CacheFirst', - }]; + it(`should support a single option with a RegExp urlPattern, using mostly defaults`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /xyz/, + handler: 'CacheFirst', + }, + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); // See https://github.com/GoogleChrome/workbox/issues/574#issue-230170963 - it(`should support multiple options, each setting multiple properties`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: 'NetworkFirst', - options: { - networkTimeoutSeconds: 20, - cacheName: 'abc-cache', - expiration: { - maxEntries: 5, - maxAgeSeconds: 50, - }, - broadcastUpdate: { - channelName: 'test', - }, - backgroundSync: { - name: 'test', - }, - precacheFallback: { - fallbackURL: '/test1', - }, - rangeRequests: false, - fetchOptions: { - headers: { - 'Custom': 'Header', + it(`should support multiple options, each setting multiple properties`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: 'NetworkFirst', + options: { + networkTimeoutSeconds: 20, + cacheName: 'abc-cache', + expiration: { + maxEntries: 5, + maxAgeSeconds: 50, + }, + broadcastUpdate: { + channelName: 'test', + }, + backgroundSync: { + name: 'test', + }, + precacheFallback: { + fallbackURL: '/test1', + }, + rangeRequests: false, + fetchOptions: { + headers: { + Custom: 'Header', + }, }, }, }, - }, { - urlPattern: '/test', - handler: 'StaleWhileRevalidate', - options: { - expiration: { - maxEntries: 10, - }, - cacheableResponse: { - statuses: [0, 200], - }, - broadcastUpdate: { - channelName: 'test', - options: { - source: 'test-source', + { + urlPattern: '/test', + handler: 'StaleWhileRevalidate', + options: { + expiration: { + maxEntries: 10, }, - }, - backgroundSync: { - name: 'test', - options: { - maxRetentionTime: 123, + cacheableResponse: { + statuses: [0, 200], + }, + broadcastUpdate: { + channelName: 'test', + options: { + source: 'test-source', + }, + }, + backgroundSync: { + name: 'test', + options: { + maxRetentionTime: 123, + }, + }, + rangeRequests: true, + precacheFallback: { + fallbackURL: '/test2', + }, + matchOptions: { + ignoreSearch: true, }, - }, - rangeRequests: true, - precacheFallback: { - fallbackURL: '/test2', - }, - matchOptions: { - ignoreSearch: true, }, }, - }]; + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); - it(`should support a string urlPattern, using mostly defaults`, function() { - const runtimeCachingOptions = [{ - urlPattern: '/path/to/file', - handler: 'CacheFirst', - }]; + it(`should support a string urlPattern, using mostly defaults`, function () { + const runtimeCachingOptions = [ + { + urlPattern: '/path/to/file', + handler: 'CacheFirst', + }, + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); - it(`should support handler being a function`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: () => {}, - }]; + it(`should support handler being a function`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: () => {}, + }, + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); - it(`should support registering non-GET methods`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: 'CacheFirst', - method: 'POST', - }]; + it(`should support registering non-GET methods`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: 'CacheFirst', + method: 'POST', + }, + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); validate(runtimeCachingOptions, convertedOptions); }); - it(`should support custom plugins`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: 'CacheFirst', - options: { - plugins: [{ - cacheWillUpdate: async ({request, response}) => { - return response; - }, - cacheDidUpdate: async ({cacheName, request, oldResponse, newResponse}) => {}, - cachedResponseWillBeUsed: async ({cacheName, request, matchOptions, cachedResponse}) => { - return cachedResponse; - }, - requestWillFetch: async ({request}) => { - return request; - }, - fetchDidFail: async ({originalRequest, request, error}) => {}, - }], + it(`should support custom plugins`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: 'CacheFirst', + options: { + plugins: [ + { + cacheWillUpdate: async ({request, response}) => { + return response; + }, + cacheDidUpdate: async ({ + cacheName, + request, + oldResponse, + newResponse, + }) => {}, + cachedResponseWillBeUsed: async ({ + cacheName, + request, + matchOptions, + cachedResponse, + }) => { + return cachedResponse; + }, + requestWillFetch: async ({request}) => { + return request; + }, + fetchDidFail: async ({originalRequest, request, error}) => {}, + }, + ], + }, }, - }]; + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); expect(convertedOptions[0].includes('cacheWillUpdate: async')).to.true; expect(convertedOptions[0].includes('cacheDidUpdate: async')).to.true; - expect(convertedOptions[0].includes('cachedResponseWillBeUsed: async')).to.true; + expect(convertedOptions[0].includes('cachedResponseWillBeUsed: async')).to + .true; expect(convertedOptions[0].includes('requestWillFetch: async')).to.true; expect(convertedOptions[0].includes('fetchDidFail: async')).to.true; }); - it(`should strip comments on custom plugins`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: 'CacheFirst', - options: { - plugins: [{ - cacheWillUpdate: async ({request, response}) => { - // Commenting - return response; - }, - cachedResponseWillBeUsed: async ({cacheName, request, matchOptions, cachedResponse}) => { - /* Commenting */ - return cachedResponse; - }, - }], + it(`should strip comments on custom plugins`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: 'CacheFirst', + options: { + plugins: [ + { + cacheWillUpdate: async ({request, response}) => { + // Commenting + return response; + }, + cachedResponseWillBeUsed: async ({ + cacheName, + request, + matchOptions, + cachedResponse, + }) => { + /* Commenting */ + return cachedResponse; + }, + }, + ], + }, }, - }]; + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); expect(convertedOptions[0].includes('// Commenting')).to.false; expect(convertedOptions[0].includes('/* Commenting */')).to.false; }); - it(`should keep contents with // that are not comments`, function() { - const runtimeCachingOptions = [{ - urlPattern: /abc/, - handler: 'CacheFirst', - options: { - plugins: [{ - cacheWillUpdate: async ({request, response}) => { - // Commenting - - if (request.url === 'https://test.com') { - return null; - } - - return response; - }, - }], + it(`should keep contents with // that are not comments`, function () { + const runtimeCachingOptions = [ + { + urlPattern: /abc/, + handler: 'CacheFirst', + options: { + plugins: [ + { + cacheWillUpdate: async ({request, response}) => { + // Commenting + + if (request.url === 'https://test.com') { + return null; + } + + return response; + }, + }, + ], + }, }, - }]; + ]; - const convertedOptions = runtimeCachingConverter(moduleRegistry, runtimeCachingOptions); + const convertedOptions = runtimeCachingConverter( + moduleRegistry, + runtimeCachingOptions, + ); expect(convertedOptions[0].includes('// Commenting')).to.false; expect(convertedOptions[0].includes('https://test.com')).to.true; }); diff --git a/test/workbox-build/node/lib/transform-manifest.js b/test/workbox-build/node/lib/transform-manifest.js index 720eed4b2..554790788 100644 --- a/test/workbox-build/node/lib/transform-manifest.js +++ b/test/workbox-build/node/lib/transform-manifest.js @@ -8,9 +8,11 @@ const expect = require('chai').expect; -const {transformManifest} = require('../../../../packages/workbox-build/build/lib/transform-manifest'); +const { + transformManifest, +} = require('../../../../packages/workbox-build/build/lib/transform-manifest'); -describe(`[workbox-build] lib/transform-manifest.js`, function() { +describe(`[workbox-build] lib/transform-manifest.js`, function () { const MAXIMUM_FILE_SIZE = 1234; const ENTRY1 = { file: 'file1.txt', @@ -29,7 +31,7 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { }; const FILE_DETAILS = [ENTRY1, ENTRY2, ENTRY3]; - it(`should filter out files above maximumFileSizeToCacheInBytes`, async function() { + it(`should filter out files above maximumFileSizeToCacheInBytes`, async function () { const {size, count, manifestEntries} = await transformManifest({ maximumFileSizeToCacheInBytes: MAXIMUM_FILE_SIZE, fileDetails: FILE_DETAILS, @@ -37,16 +39,19 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { expect(size).to.eql(ENTRY1.size + ENTRY2.size); expect(count).to.eql(2); - expect(manifestEntries).to.deep.equal([{ - url: ENTRY1.file, - revision: ENTRY1.hash, - }, { - url: ENTRY2.file, - revision: ENTRY2.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: ENTRY1.file, + revision: ENTRY1.hash, + }, + { + url: ENTRY2.file, + revision: ENTRY2.hash, + }, + ]); }); - it(`should remove revision info based on dontCacheBustURLsMatching`, async function() { + it(`should remove revision info based on dontCacheBustURLsMatching`, async function () { const {size, count, manifestEntries} = await transformManifest({ dontCacheBustURLsMatching: new RegExp(ENTRY1.file), fileDetails: FILE_DETAILS, @@ -54,19 +59,23 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { expect(size).to.eql(ENTRY1.size + ENTRY2.size + ENTRY3.size); expect(count).to.eql(3); - expect(manifestEntries).to.deep.equal([{ - url: ENTRY1.file, - revision: null, - }, { - url: ENTRY2.file, - revision: ENTRY2.hash, - }, { - url: ENTRY3.file, - revision: ENTRY3.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: ENTRY1.file, + revision: null, + }, + { + url: ENTRY2.file, + revision: ENTRY2.hash, + }, + { + url: ENTRY3.file, + revision: ENTRY3.hash, + }, + ]); }); - it(`should modify the URLs based on modifyURLPrefix`, async function() { + it(`should modify the URLs based on modifyURLPrefix`, async function () { const prefix = 'prefix/'; const {size, count, manifestEntries} = await transformManifest({ @@ -78,19 +87,23 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { expect(size).to.eql(ENTRY1.size + ENTRY2.size + ENTRY3.size); expect(count).to.eql(3); - expect(manifestEntries).to.deep.equal([{ - url: prefix + ENTRY1.file, - revision: ENTRY1.hash, - }, { - url: prefix + ENTRY2.file, - revision: ENTRY2.hash, - }, { - url: prefix + ENTRY3.file, - revision: ENTRY3.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: prefix + ENTRY1.file, + revision: ENTRY1.hash, + }, + { + url: prefix + ENTRY2.file, + revision: ENTRY2.hash, + }, + { + url: prefix + ENTRY3.file, + revision: ENTRY3.hash, + }, + ]); }); - it(`should use custom manifestTransforms`, async function() { + it(`should use custom manifestTransforms`, async function () { const prefix1 = 'prefix1/'; const prefix2 = 'prefix2/'; @@ -128,19 +141,23 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { expect(warnings).to.eql([warning1, warning2]); expect(size).to.eql(ENTRY1.size + ENTRY2.size + ENTRY3.size); expect(count).to.eql(3); - expect(manifestEntries).to.deep.equal([{ - url: prefix2 + prefix1 + ENTRY1.file, - revision: ENTRY1.hash, - }, { - url: prefix2 + prefix1 + ENTRY2.file, - revision: ENTRY2.hash, - }, { - url: prefix2 + prefix1 + ENTRY3.file, - revision: ENTRY3.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: prefix2 + prefix1 + ENTRY1.file, + revision: ENTRY1.hash, + }, + { + url: prefix2 + prefix1 + ENTRY2.file, + revision: ENTRY2.hash, + }, + { + url: prefix2 + prefix1 + ENTRY3.file, + revision: ENTRY3.hash, + }, + ]); }); - it(`should support an async manifestTransform`, async function() { + it(`should support an async manifestTransform`, async function () { const asyncTransform = async (manifest) => { await Promise.resolve(); return {manifest, warnings: []}; @@ -154,15 +171,19 @@ describe(`[workbox-build] lib/transform-manifest.js`, function() { expect(warnings).to.be.empty; expect(size).to.eql(ENTRY1.size + ENTRY2.size + ENTRY3.size); expect(count).to.eql(3); - expect(manifestEntries).to.deep.equal([{ - url: ENTRY1.file, - revision: ENTRY1.hash, - }, { - url: ENTRY2.file, - revision: ENTRY2.hash, - }, { - url: ENTRY3.file, - revision: ENTRY3.hash, - }]); + expect(manifestEntries).to.deep.equal([ + { + url: ENTRY1.file, + revision: ENTRY1.hash, + }, + { + url: ENTRY2.file, + revision: ENTRY2.hash, + }, + { + url: ENTRY3.file, + revision: ENTRY3.hash, + }, + ]); }); }); diff --git a/test/workbox-build/node/lib/validate-options.js b/test/workbox-build/node/lib/validate-options.js index e0b12b22f..a4d6ef45c 100644 --- a/test/workbox-build/node/lib/validate-options.js +++ b/test/workbox-build/node/lib/validate-options.js @@ -31,8 +31,9 @@ class AJVPassesValidation { } // The integration tests will exercise the actual validation logic. -describe(`[workbox-build] entry-points/options/validate-options.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/validate-options'; +describe(`[workbox-build] entry-points/options/validate-options.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/validate-options'; const testCases = [ 'validateGenerateSWOptions', 'validateGetManifestOptions', @@ -40,33 +41,36 @@ describe(`[workbox-build] entry-points/options/validate-options.js`, function() ]; for (const func of testCases) { - it(`${func}() should throw when validation fails`, function() { + it(`${func}() should throw when validation fails`, function () { const validateOptions = proxyquire(MODULE_PATH, { 'ajv': { default: AJVFailsValidation, }, '@apideck/better-ajv-errors': { - betterAjvErrors: sinon.stub().returns([{ - message: 'message1', - path: 'path1', - suggestion: 'suggestion1', - }, { - message: 'message2', - path: 'path2', - suggestion: 'suggestion2', - }]), + betterAjvErrors: sinon.stub().returns([ + { + message: 'message1', + path: 'path1', + suggestion: 'suggestion1', + }, + { + message: 'message2', + path: 'path2', + suggestion: 'suggestion2', + }, + ]), }, }); expect(() => validateOptions[func]()).to.throw( - validateOptions.WorkboxConfigError, - `[path1] message1. suggestion1\n\n[path2] message2. suggestion2`, + validateOptions.WorkboxConfigError, + `[path1] message1. suggestion1\n\n[path2] message2. suggestion2`, ); }); - it(`${func}() should not throw when validation passes`, function() { + it(`${func}() should not throw when validation passes`, function () { const validateOptions = proxyquire(MODULE_PATH, { - 'ajv': { + ajv: { default: AJVPassesValidation, }, }); diff --git a/test/workbox-build/node/lib/write-sw-using-default-template.js b/test/workbox-build/node/lib/write-sw-using-default-template.js index 67b18b9f8..e7387c6de 100644 --- a/test/workbox-build/node/lib/write-sw-using-default-template.js +++ b/test/workbox-build/node/lib/write-sw-using-default-template.js @@ -13,10 +13,11 @@ const sinon = require('sinon'); const {errors} = require('../../../../packages/workbox-build/build/lib/errors'); -describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { - const MODULE_PATH = '../../../../packages/workbox-build/build/lib/write-sw-using-default-template'; +describe(`[workbox-build] lib/write-sw-using-default-template.js`, function () { + const MODULE_PATH = + '../../../../packages/workbox-build/build/lib/write-sw-using-default-template'; - it(`should reject with an error when fs-extra.mkdirp() fails`, async function() { + it(`should reject with an error when fs-extra.mkdirp() fails`, async function () { const {writeSWUsingDefaultTemplate} = proxyquire(MODULE_PATH, { 'upath': { dirname: () => 'ignored', @@ -30,11 +31,13 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { await writeSWUsingDefaultTemplate({}); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.have.string(errors['unable-to-make-sw-directory']); + expect(error.message).to.have.string( + errors['unable-to-make-sw-directory'], + ); } }); - it(`should reject with an error when fs-extra.writeFile() fails`, async function() { + it(`should reject with an error when fs-extra.writeFile() fails`, async function () { const {writeSWUsingDefaultTemplate} = proxyquire(MODULE_PATH, { 'upath': { dirname: () => 'ignored', @@ -53,7 +56,7 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { } }); - it(`should reject with a specific error when fs-extra.writeFile() fails due to EISDIR`, async function() { + it(`should reject with a specific error when fs-extra.writeFile() fails due to EISDIR`, async function () { const eisdirError = new Error(); eisdirError.code = 'EISDIR'; @@ -67,10 +70,12 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { writeFile: () => Promise.reject(eisdirError), }, './bundle': { - bundle: async () => [{ - name: 'ignored', - contents: 'ignored', - }], + bundle: async () => [ + { + name: 'ignored', + contents: 'ignored', + }, + ], }, }); @@ -78,11 +83,13 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { await writeSWUsingDefaultTemplate({manifestEntries: ['ignored']}); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.have.string(errors['sw-write-failure-directory']); + expect(error.message).to.have.string( + errors['sw-write-failure-directory'], + ); } }); - it(`should call fs-extra.writeFile() with the expected parameters when everything succeeds`, async function() { + it(`should call fs-extra.writeFile() with the expected parameters when everything succeeds`, async function () { const expectedPath = upath.join('expected', 'path'); const swDest = upath.join(expectedPath, 'sw.js'); const file1 = 'file1.js'; @@ -100,13 +107,16 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { writeFile: writeFileStub, }, './bundle': { - bundle: async () => [{ - name: upath.join(expectedPath, file1), - contents: contents1, - }, { - name: upath.join(expectedPath, file2), - contents: contents2, - }], + bundle: async () => [ + { + name: upath.join(expectedPath, file1), + contents: contents1, + }, + { + name: upath.join(expectedPath, file2), + contents: contents2, + }, + ], }, './populate-sw-template': { populateSWTemplate: () => '', @@ -116,12 +126,9 @@ describe(`[workbox-build] lib/write-sw-using-default-template.js`, function() { await writeSWUsingDefaultTemplate({swDest}); // There should be exactly two calls to fs-extra.writeFile(). - expect(writeFileStub.args).to.eql([[ - upath.resolve(expectedPath, file1), - contents1, - ], [ - upath.resolve(expectedPath, file2), - contents2, - ]]); + expect(writeFileStub.args).to.eql([ + [upath.resolve(expectedPath, file1), contents1], + [upath.resolve(expectedPath, file2), contents2], + ]); }); }); diff --git a/test/workbox-build/static/example-project-1/index.html b/test/workbox-build/static/example-project-1/index.html index 070a6d27e..bfc1ee34b 100644 --- a/test/workbox-build/static/example-project-1/index.html +++ b/test/workbox-build/static/example-project-1/index.html @@ -4,12 +4,12 @@

    Index

    // Helper function which returns a promise which resolves once the service worker registration // is past the "installing" state. function waitUntilInstalled(registration) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { if (registration.installing) { // If the current registration represents the "installing" service worker, then wait // until the installation step (during which the resources are pre-fetched) completes // to display the file list. - registration.installing.addEventListener('statechange', function(e) { + registration.installing.addEventListener('statechange', function (e) { if (e.target.state === 'installed') { resolve(); } else if (e.target.state === 'redundant') { @@ -35,40 +35,42 @@

    Index

    } searchParams[split[0]] = decodeURIComponent(split[1]); }); - navigator.serviceWorker.register(searchParams.sw) - .then((registration) => { - return waitUntilInstalled(registration); - }) - .then(() => { - return window.caches.keys() - .then(keys => { - return window.caches.open(keys[0]); + navigator.serviceWorker + .register(searchParams.sw) + .then((registration) => { + return waitUntilInstalled(registration); }) - .then((cache) => { - return cache.keys(); - }); - }) - .then((entries) => { - window.__testresult = { - entries: entries.map((entry) => { - return entry.url; - }) - }; - }) - .catch((err) => { - document.body.style.color = 'red'; - document.body.innerHTML = `

    ${err.message}

    + .then(() => { + return window.caches + .keys() + .then((keys) => { + return window.caches.open(keys[0]); + }) + .then((cache) => { + return cache.keys(); + }); + }) + .then((entries) => { + window.__testresult = { + entries: entries.map((entry) => { + return entry.url; + }), + }; + }) + .catch((err) => { + document.body.style.color = 'red'; + document.body.innerHTML = `

    ${err.message}

    ${err.stack}
    `; - console.error(err.message) - console.error(err.stack); + console.error(err.message); + console.error(err.stack); - // This is just to help with local development so we know there is an error - setTimeout(() => { - window.__testresult = { - error: err - }; - }, 5 * 1000); - }); + // This is just to help with local development so we know there is an error + setTimeout(() => { + window.__testresult = { + error: err, + }; + }, 5 * 1000); + }); diff --git a/test/workbox-build/static/example-project-1/webpackEntry.js b/test/workbox-build/static/example-project-1/webpackEntry.js index 3aa4377e0..f16da490e 100644 --- a/test/workbox-build/static/example-project-1/webpackEntry.js +++ b/test/workbox-build/static/example-project-1/webpackEntry.js @@ -5,4 +5,3 @@ license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ - diff --git a/test/workbox-build/static/sw-injections/sample-import.js b/test/workbox-build/static/sw-injections/sample-import.js index 3aa4377e0..f16da490e 100644 --- a/test/workbox-build/static/sw-injections/sample-import.js +++ b/test/workbox-build/static/sw-injections/sample-import.js @@ -5,4 +5,3 @@ license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. */ - diff --git a/test/workbox-cacheable-response/integration/test-all.js b/test/workbox-cacheable-response/integration/test-all.js index b28a1e238..d30f2308c 100644 --- a/test/workbox-cacheable-response/integration/test-all.js +++ b/test/workbox-cacheable-response/integration/test-all.js @@ -13,32 +13,33 @@ const runInSW = require('../../../infra/testing/comlink/node-interface'); const waitUntil = require('../../../infra/testing/wait-until'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-cacheable-response]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-cacheable-response]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-cacheable-response/sw/'); }); }); -describe(`[workbox-cacheable-response] Plugin`, function() { +describe(`[workbox-cacheable-response] Plugin`, function () { const baseURL = `${server.getAddress()}/test/workbox-cacheable-response/static/cacheable-response-plugin/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(webdriver, `${baseURL}integration.html`); }); - it(`should load a page and cache entries`, async function() { + it(`should load a page and cache entries`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. await activateAndControlSW(swURL); const error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-1.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-1.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -52,13 +53,9 @@ describe(`[workbox-cacheable-response] Plugin`, function() { }); const keys = await runInSW('cachesKeys'); - expect(keys).to.deep.equal([ - 'cacheable-response-cache', - ]); + expect(keys).to.deep.equal(['cacheable-response-cache']); const cachedRequests = await runInSW('cacheURLs', keys[0]); - expect(cachedRequests).to.eql([ - `${baseURL}example-1.txt`, - ]); + expect(cachedRequests).to.eql([`${baseURL}example-1.txt`]); }); }); diff --git a/test/workbox-cacheable-response/static/cacheable-response-plugin/sw.js b/test/workbox-cacheable-response/static/cacheable-response-plugin/sw.js index ab1b2ce3b..89c5298ca 100644 --- a/test/workbox-cacheable-response/static/cacheable-response-plugin/sw.js +++ b/test/workbox-cacheable-response/static/cacheable-response-plugin/sw.js @@ -13,16 +13,20 @@ importScripts('/__WORKBOX/buildFile/workbox-strategies'); importScripts('/infra/testing/comlink/sw-interface.js'); workbox.routing.registerRoute( - /.*.txt/, - new workbox.strategies.CacheFirst({ - cacheName: 'cacheable-response-cache', - plugins: [ - new workbox.cacheableResponse.CacheableResponsePlugin({ - statuses: [0, 200], - }), - ], - }), + /.*.txt/, + new workbox.strategies.CacheFirst({ + cacheName: 'cacheable-response-cache', + plugins: [ + new workbox.cacheableResponse.CacheableResponsePlugin({ + statuses: [0, 200], + }), + ], + }), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-cacheable-response/sw/test-CacheableResponse.mjs b/test/workbox-cacheable-response/sw/test-CacheableResponse.mjs index fd4ac6d53..a5040d254 100644 --- a/test/workbox-cacheable-response/sw/test-CacheableResponse.mjs +++ b/test/workbox-cacheable-response/sw/test-CacheableResponse.mjs @@ -8,8 +8,7 @@ import {CacheableResponse} from 'workbox-cacheable-response/CacheableResponse.mjs'; - -describe(`CacheableResponse`, function() { +describe(`CacheableResponse`, function () { const VALID_STATUS = 418; const INVALID_STATUS = 500; const VALID_STATUSES = [VALID_STATUS]; @@ -17,58 +16,94 @@ describe(`CacheableResponse`, function() { 'x-test': 'true', }; - describe(`constructor`, function() { - it(`should throw with no config`, async function() { + describe(`constructor`, function () { + it(`should throw with no config`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); - await expectError(() => { - new CacheableResponse(); - }, 'statuses-or-headers-required', (err) => { - expect(err.details).to.have.property('moduleName').that.eql('workbox-cacheable-response'); - expect(err.details).to.have.property('className').that.eql('CacheableResponse'); - expect(err.details).to.have.property('funcName').that.eql('constructor'); - }); + await expectError( + () => { + new CacheableResponse(); + }, + 'statuses-or-headers-required', + (err) => { + expect(err.details) + .to.have.property('moduleName') + .that.eql('workbox-cacheable-response'); + expect(err.details) + .to.have.property('className') + .that.eql('CacheableResponse'); + expect(err.details) + .to.have.property('funcName') + .that.eql('constructor'); + }, + ); }); - it(`should throw with bad config.statuses`, async function() { + it(`should throw with bad config.statuses`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); - await expectError(() => { - new CacheableResponse({statuses: 'bad input'}); - }, 'not-an-array', (err) => { - expect(err.details).to.have.property('moduleName').that.eql('workbox-cacheable-response'); - expect(err.details).to.have.property('className').that.eql('CacheableResponse'); - expect(err.details).to.have.property('funcName').that.eql('constructor'); - expect(err.details).to.have.property('paramName').that.eql('config.statuses'); - }); + await expectError( + () => { + new CacheableResponse({statuses: 'bad input'}); + }, + 'not-an-array', + (err) => { + expect(err.details) + .to.have.property('moduleName') + .that.eql('workbox-cacheable-response'); + expect(err.details) + .to.have.property('className') + .that.eql('CacheableResponse'); + expect(err.details) + .to.have.property('funcName') + .that.eql('constructor'); + expect(err.details) + .to.have.property('paramName') + .that.eql('config.statuses'); + }, + ); }); - it(`should throw with bad config.headers`, async function() { + it(`should throw with bad config.headers`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); - await expectError(() => { - new CacheableResponse({headers: 'bad input'}); - }, 'incorrect-type', (err) => { - expect(err.details).to.have.property('moduleName').that.eql('workbox-cacheable-response'); - expect(err.details).to.have.property('className').that.eql('CacheableResponse'); - expect(err.details).to.have.property('funcName').that.eql('constructor'); - expect(err.details).to.have.property('paramName').that.eql('config.headers'); - }); + await expectError( + () => { + new CacheableResponse({headers: 'bad input'}); + }, + 'incorrect-type', + (err) => { + expect(err.details) + .to.have.property('moduleName') + .that.eql('workbox-cacheable-response'); + expect(err.details) + .to.have.property('className') + .that.eql('CacheableResponse'); + expect(err.details) + .to.have.property('funcName') + .that.eql('constructor'); + expect(err.details) + .to.have.property('paramName') + .that.eql('config.headers'); + }, + ); }); - it(`should be able to construct with config.statuses`, function() { - const cacheableResponse = new CacheableResponse({statuses: VALID_STATUSES}); + it(`should be able to construct with config.statuses`, function () { + const cacheableResponse = new CacheableResponse({ + statuses: VALID_STATUSES, + }); expect(cacheableResponse._statuses).to.eql(VALID_STATUSES); }); - it(`should be able to construct with config.headers`, function() { + it(`should be able to construct with config.headers`, function () { const cacheableResponse = new CacheableResponse({headers: VALID_HEADERS}); expect(cacheableResponse._headers).to.eql(VALID_HEADERS); }); - it(`should be able to construct with config.statuses and config.headers`, function() { + it(`should be able to construct with config.statuses and config.headers`, function () { const cacheableResponse = new CacheableResponse({ statuses: VALID_STATUSES, headers: VALID_HEADERS, @@ -79,43 +114,61 @@ describe(`CacheableResponse`, function() { }); }); - describe(`isResponseCacheable`, function() { - it(`should throw when passed bad input`, async function() { + describe(`isResponseCacheable`, function () { + it(`should throw when passed bad input`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); - const cacheableResponse = new CacheableResponse({statuses: VALID_STATUSES}); - await expectError(() => { - cacheableResponse.isResponseCacheable(null); - }, 'incorrect-class', (err) => { - expect(err.details).to.have.property('moduleName').that.eql('workbox-cacheable-response'); - expect(err.details).to.have.property('className').that.eql('CacheableResponse'); - expect(err.details).to.have.property('funcName').that.eql('isResponseCacheable'); - expect(err.details).to.have.property('paramName').that.eql('response'); + const cacheableResponse = new CacheableResponse({ + statuses: VALID_STATUSES, }); + await expectError( + () => { + cacheableResponse.isResponseCacheable(null); + }, + 'incorrect-class', + (err) => { + expect(err.details) + .to.have.property('moduleName') + .that.eql('workbox-cacheable-response'); + expect(err.details) + .to.have.property('className') + .that.eql('CacheableResponse'); + expect(err.details) + .to.have.property('funcName') + .that.eql('isResponseCacheable'); + expect(err.details) + .to.have.property('paramName') + .that.eql('response'); + }, + ); }); - it(`should return true when one of the statuses match the response`, function() { - const cacheableResponse = new CacheableResponse({statuses: VALID_STATUSES}); + it(`should return true when one of the statuses match the response`, function () { + const cacheableResponse = new CacheableResponse({ + statuses: VALID_STATUSES, + }); const response = new Response('', {status: VALID_STATUS}); expect(cacheableResponse.isResponseCacheable(response)).to.be.true; }); - it(`should return false when none of the statuses match the response`, function() { - const cacheableResponse = new CacheableResponse({statuses: VALID_STATUSES}); + it(`should return false when none of the statuses match the response`, function () { + const cacheableResponse = new CacheableResponse({ + statuses: VALID_STATUSES, + }); const response = new Response('', {status: INVALID_STATUS}); expect(cacheableResponse.isResponseCacheable(response)).to.be.false; }); - it(`should return true when one of the headers match the response`, function() { + it(`should return true when one of the headers match the response`, function () { const cacheableResponse = new CacheableResponse({headers: VALID_HEADERS}); const response = new Response('', {headers: VALID_HEADERS}); expect(cacheableResponse.isResponseCacheable(response)).to.be.true; }); - it(`should return false when none of the headers match the response`, function() { + it(`should return false when none of the headers match the response`, function () { const cacheableResponse = new CacheableResponse({headers: VALID_HEADERS}); const response = new Response('', { headers: { @@ -126,7 +179,7 @@ describe(`CacheableResponse`, function() { expect(cacheableResponse.isResponseCacheable(response)).to.be.false; }); - it(`should return false when one of the statuses match the response, but none of the headers match`, function() { + it(`should return false when one of the statuses match the response, but none of the headers match`, function () { const cacheableResponse = new CacheableResponse({ statuses: VALID_STATUSES, headers: VALID_HEADERS, @@ -136,7 +189,7 @@ describe(`CacheableResponse`, function() { expect(cacheableResponse.isResponseCacheable(response)).to.be.false; }); - it(`should return false when one of the headers match the response, but none of the statuses match`, function() { + it(`should return false when one of the headers match the response, but none of the statuses match`, function () { const cacheableResponse = new CacheableResponse({ statuses: VALID_STATUSES, headers: VALID_HEADERS, @@ -149,7 +202,7 @@ describe(`CacheableResponse`, function() { expect(cacheableResponse.isResponseCacheable(response)).to.be.false; }); - it(`should return true when both the headers and statuses match the response`, function() { + it(`should return true when both the headers and statuses match the response`, function () { const cacheableResponse = new CacheableResponse({ statuses: VALID_STATUSES, headers: VALID_HEADERS, diff --git a/test/workbox-cacheable-response/sw/test-CacheableResponsePlugin.mjs b/test/workbox-cacheable-response/sw/test-CacheableResponsePlugin.mjs index 28281f912..fb501485a 100644 --- a/test/workbox-cacheable-response/sw/test-CacheableResponsePlugin.mjs +++ b/test/workbox-cacheable-response/sw/test-CacheableResponsePlugin.mjs @@ -9,30 +9,40 @@ import {CacheableResponse} from 'workbox-cacheable-response/CacheableResponse.mjs'; import {CacheableResponsePlugin} from 'workbox-cacheable-response/CacheableResponsePlugin.mjs'; - -describe(`CacheableResponsePlugin`, function() { +describe(`CacheableResponsePlugin`, function () { const STATUSES = [200]; const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`should construct a properly-configured internal CacheableResponse instance`, function() { - const cacheableResponsePlugin = new CacheableResponsePlugin({statuses: STATUSES}); - expect(cacheableResponsePlugin._cacheableResponse).to.be.instanceOf(CacheableResponse); - expect(cacheableResponsePlugin._cacheableResponse._statuses).to.eql(STATUSES); + describe(`constructor`, function () { + it(`should construct a properly-configured internal CacheableResponse instance`, function () { + const cacheableResponsePlugin = new CacheableResponsePlugin({ + statuses: STATUSES, + }); + expect(cacheableResponsePlugin._cacheableResponse).to.be.instanceOf( + CacheableResponse, + ); + expect(cacheableResponsePlugin._cacheableResponse._statuses).to.eql( + STATUSES, + ); }); - it(`should expose cacheWillUpdate, which calls cacheableResponse.isResponseCacheable()`, function() { - const cacheableResponsePlugin = new CacheableResponsePlugin({statuses: STATUSES}); - const isResponseCacheableSpy = sandbox.spy(cacheableResponsePlugin._cacheableResponse, 'isResponseCacheable'); + it(`should expose cacheWillUpdate, which calls cacheableResponse.isResponseCacheable()`, function () { + const cacheableResponsePlugin = new CacheableResponsePlugin({ + statuses: STATUSES, + }); + const isResponseCacheableSpy = sandbox.spy( + cacheableResponsePlugin._cacheableResponse, + 'isResponseCacheable', + ); const response = new Response(''); cacheableResponsePlugin.cacheWillUpdate({response}); @@ -41,13 +51,19 @@ describe(`CacheableResponsePlugin`, function() { }); }); - describe(`cacheWillUpdate`, function() { - it(`should return null for non-cachable response`, async function() { - const cacheableResponsePlugin = new CacheableResponsePlugin({statuses: STATUSES}); - sandbox.stub(cacheableResponsePlugin._cacheableResponse, 'isResponseCacheable').callsFake(() => false); - expect(await cacheableResponsePlugin.cacheWillUpdate({ - response: new Response(), - })).to.equal(null); + describe(`cacheWillUpdate`, function () { + it(`should return null for non-cachable response`, async function () { + const cacheableResponsePlugin = new CacheableResponsePlugin({ + statuses: STATUSES, + }); + sandbox + .stub(cacheableResponsePlugin._cacheableResponse, 'isResponseCacheable') + .callsFake(() => false); + expect( + await cacheableResponsePlugin.cacheWillUpdate({ + response: new Response(), + }), + ).to.equal(null); }); }); }); diff --git a/test/workbox-cli/node/app.js b/test/workbox-cli/node/app.js index 122e3e844..8904c9cb9 100644 --- a/test/workbox-cli/node/app.js +++ b/test/workbox-cli/node/app.js @@ -12,14 +12,18 @@ const proxyquire = require('proxyquire'); const sinon = require('sinon'); const upath = require('upath'); -const {constants} = require('../../../packages/workbox-cli/build/lib/constants'); +const { + constants, +} = require('../../../packages/workbox-cli/build/lib/constants'); const {errors} = require('../../../packages/workbox-cli/build/lib/errors'); -const {WorkboxConfigError} = require('../../../packages/workbox-build/build/lib/validate-options'); +const { + WorkboxConfigError, +} = require('../../../packages/workbox-build/build/lib/validate-options'); chai.use(chaiAsPromised); const {expect} = chai; -describe(`[workbox-cli] app.js`, function() { +describe(`[workbox-cli] app.js`, function () { const MODULE_PATH = '../../../packages/workbox-cli/build/app'; const PROXIED_CONFIG_FILE = upath.resolve(process.cwd(), '/will/be/proxied'); const PROXIED_DEST_DIR = upath.resolve(process.cwd(), 'build'); @@ -28,12 +32,12 @@ describe(`[workbox-cli] app.js`, function() { globDirectory: '.', swDest: 'sw.js', }; - const INVALID_CONFIG_FILE = upath.resolve(process.cwd(), upath.join('does', 'not', 'exist')); + const INVALID_CONFIG_FILE = upath.resolve( + process.cwd(), + upath.join('does', 'not', 'exist'), + ); const UNKNOWN_COMMAND = 'unknown-command'; - const WORKBOX_BUILD_COMMANDS = [ - 'generateSW', - 'injectManifest', - ]; + const WORKBOX_BUILD_COMMANDS = ['generateSW', 'injectManifest']; const WORKBOX_BUILD_NO_WARNINGS_RETURN_VALUE = { count: 1, filePaths: ['ignored1', 'ignored2'], @@ -47,26 +51,29 @@ describe(`[workbox-cli] app.js`, function() { warnings: ['warning'], }; - describe(`failures due to bad parameters`, function() { + describe(`failures due to bad parameters`, function () { const {app} = require(MODULE_PATH); - it(`should reject when both parameters are missing`, async function() { + it(`should reject when both parameters are missing`, async function () { await expect(app()).to.eventually.be.rejectedWith( - errors['missing-input']); + errors['missing-input'], + ); }); - it(`should reject when the command is unknown and options is present`, async function() { - await expect(app({input: [UNKNOWN_COMMAND, PROXIED_CONFIG_FILE]})).to - .eventually.be.rejectedWith(errors['unknown-command']); + it(`should reject when the command is unknown and options is present`, async function () { + await expect( + app({input: [UNKNOWN_COMMAND, PROXIED_CONFIG_FILE]}), + ).to.eventually.be.rejectedWith(errors['unknown-command']); }); - it(`should reject when the command parameter is copyLibraries and options is missing`, async function() { - await expect(app({input: ['copyLibraries']})).to - .eventually.be.rejectedWith(errors['missing-dest-dir-param']); + it(`should reject when the command parameter is copyLibraries and options is missing`, async function () { + await expect( + app({input: ['copyLibraries']}), + ).to.eventually.be.rejectedWith(errors['missing-dest-dir-param']); }); for (const command of WORKBOX_BUILD_COMMANDS) { - it(`should reject when the command parameter is ${command} and options does not exist`, async function() { + it(`should reject when the command parameter is ${command} and options does not exist`, async function () { const loggerErrorStub = sinon.stub(); const {app} = proxyquire(MODULE_PATH, { './lib/logger.js': { @@ -80,7 +87,9 @@ describe(`[workbox-cli] app.js`, function() { } catch (error) { expect(loggerErrorStub.calledOnce).to.be.true; expect( - loggerErrorStub.alwaysCalledWithExactly(errors['invalid-common-js-module']), + loggerErrorStub.alwaysCalledWithExactly( + errors['invalid-common-js-module'], + ), ).to.be.true; expect(error.message).to.have.string(INVALID_CONFIG_FILE); @@ -89,7 +98,7 @@ describe(`[workbox-cli] app.js`, function() { } }); - describe(`failures due to workbox-build runtime errors`, function() { + describe(`failures due to workbox-build runtime errors`, function () { for (const command of WORKBOX_BUILD_COMMANDS) { // TODO: Expand this list. const badConfigs = [ @@ -100,7 +109,9 @@ describe(`[workbox-cli] app.js`, function() { ]; for (const config of badConfigs) { - it(`should reject with a WorkboxConfigError when workbox-build.${command}(${JSON.stringify(config)}) is called`, async function() { + it(`should reject with a WorkboxConfigError when workbox-build.${command}(${JSON.stringify( + config, + )}) is called`, async function () { const {app} = proxyquire(MODULE_PATH, { './lib/logger': { logger: { @@ -116,12 +127,13 @@ describe(`[workbox-cli] app.js`, function() { }, }); - await expect(app({input: [command, PROXIED_CONFIG_FILE]})).to - .eventually.be.rejectedWith(WorkboxConfigError); + await expect( + app({input: [command, PROXIED_CONFIG_FILE]}), + ).to.eventually.be.rejectedWith(WorkboxConfigError); }); } - it(`should reject with a generic runtime error when the workbox-build.${command}() rejects for any other reason`, async function() { + it(`should reject with a generic runtime error when the workbox-build.${command}() rejects for any other reason`, async function () { const {app} = proxyquire(MODULE_PATH, { './lib/logger': { logger: { @@ -142,15 +154,16 @@ describe(`[workbox-cli] app.js`, function() { }, }); - await expect(app({input: [command, PROXIED_CONFIG_FILE]})).to - .eventually.be.rejectedWith(PROXIED_ERROR); + await expect( + app({input: [command, PROXIED_CONFIG_FILE]}), + ).to.eventually.be.rejectedWith(PROXIED_ERROR); }); } }); - describe(`successful calls`, function() { + describe(`successful calls`, function () { for (const command of WORKBOX_BUILD_COMMANDS) { - it(`should call logger.log() upon successfully running workbox-build.${command}()`, async function() { + it(`should call logger.log() upon successfully running workbox-build.${command}()`, async function () { const loggerLogStub = sinon.stub(); const {app} = proxyquire(MODULE_PATH, { './lib/read-config': { @@ -175,7 +188,7 @@ describe(`[workbox-cli] app.js`, function() { expect(loggerLogStub.callCount).to.eql(3); }); - it(`should call logger.warn() to report warnings, and then logger.log() upon successfully running workbox-build.${command}()`, async function() { + it(`should call logger.warn() to report warnings, and then logger.log() upon successfully running workbox-build.${command}()`, async function () { const loggerLogStub = sinon.stub(); const loggerWarningStub = sinon.stub(); const {app} = proxyquire(MODULE_PATH, { @@ -203,12 +216,15 @@ describe(`[workbox-cli] app.js`, function() { expect(loggerLogStub.callCount).to.eql(3); }); - it(`should call logger.log() upon successfully running workbox-build.${command}() using the default config file location`, async function() { + it(`should call logger.log() upon successfully running workbox-build.${command}() using the default config file location`, async function () { const loggerLogStub = sinon.stub(); const {app} = proxyquire(MODULE_PATH, { './lib/read-config': { readConfig: (options) => { - const defaultConfigPath = upath.join(process.cwd(), constants.defaultConfigFile); + const defaultConfigPath = upath.join( + process.cwd(), + constants.defaultConfigFile, + ); expect(options).to.eql(defaultConfigPath); return PROXIED_CONFIG; }, @@ -231,7 +247,7 @@ describe(`[workbox-cli] app.js`, function() { }); } - it(`should call logger.log() upon successfully running workbox-build.copyWorkboxLibraries()`, async function() { + it(`should call logger.log() upon successfully running workbox-build.copyWorkboxLibraries()`, async function () { const loggerLogStub = sinon.stub(); const {app} = proxyquire(MODULE_PATH, { './lib/logger': { @@ -251,7 +267,7 @@ describe(`[workbox-cli] app.js`, function() { expect(loggerLogStub.callCount).to.eql(3); }); - it(`should call params.showHelp() when passed 'help'`, async function() { + it(`should call params.showHelp() when passed 'help'`, async function () { const {app} = require(MODULE_PATH); const params = { @@ -263,7 +279,7 @@ describe(`[workbox-cli] app.js`, function() { expect(params.showHelp.calledOnce).to.be.true; }); - it(`should call params.showHelp() when not passed any command`, async function() { + it(`should call params.showHelp() when not passed any command`, async function () { const {app} = require(MODULE_PATH); const params = { diff --git a/test/workbox-cli/node/dependency-check.js b/test/workbox-cli/node/dependency-check.js index c7bb5dcb2..43de8286a 100644 --- a/test/workbox-cli/node/dependency-check.js +++ b/test/workbox-cli/node/dependency-check.js @@ -9,35 +9,53 @@ const depcheck = require('depcheck'); const upath = require('upath'); -describe(`[workbox-cli] package.json`, function() { - it(`should have required dependencies`, function() { +describe(`[workbox-cli] package.json`, function () { + it(`should have required dependencies`, function () { return new Promise((resolve, reject) => { - depcheck(upath.join(__dirname, '..', '..', '..', 'packages', 'workbox-cli'), { - ignoreDirs: [ - 'build', - ], - ignoreMatches: [ - '@babel/runtime', - ], - }, (unusedDeps) => { - if (unusedDeps.dependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.dependencies)}`)); - } + depcheck( + upath.join(__dirname, '..', '..', '..', 'packages', 'workbox-cli'), + { + ignoreDirs: ['build'], + ignoreMatches: ['@babel/runtime'], + }, + (unusedDeps) => { + if (unusedDeps.dependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.dependencies, + )}`, + ), + ); + } - if (unusedDeps.devDependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.devDependencies)}`)); - } + if (unusedDeps.devDependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.devDependencies, + )}`, + ), + ); + } - if (Object.keys(unusedDeps.missing).length > 0) { - return reject(new Error(`Dependencies missing from package.json: ${JSON.stringify(unusedDeps.missing)}`)); - } + if (Object.keys(unusedDeps.missing).length > 0) { + return reject( + new Error( + `Dependencies missing from package.json: ${JSON.stringify( + unusedDeps.missing, + )}`, + ), + ); + } - resolve(); - }); + resolve(); + }, + ); }); }); - it(`should have no devDependencies`, function() { + it(`should have no devDependencies`, function () { const pkg = require('../../../packages/workbox-cli/package.json'); if (pkg.devDependencies && Object.keys(pkg.devDependencies) > 0) { throw new Error('There should not be devDependencies in this module.'); diff --git a/test/workbox-cli/node/lib/cleanup-stack-trace.js b/test/workbox-cli/node/lib/cleanup-stack-trace.js index e42f4b604..2c3372446 100644 --- a/test/workbox-cli/node/lib/cleanup-stack-trace.js +++ b/test/workbox-cli/node/lib/cleanup-stack-trace.js @@ -9,25 +9,27 @@ const expect = require('chai').expect; const upath = require('upath'); -const {cleanupStackTrace} = require('../../../../packages/workbox-cli/build/lib/cleanup-stack-trace'); +const { + cleanupStackTrace, +} = require('../../../../packages/workbox-cli/build/lib/cleanup-stack-trace'); -describe(`[workbox-cli] lib/cleanup-stack-trace.js`, function() { +describe(`[workbox-cli] lib/cleanup-stack-trace.js`, function () { const CURRENT_MODULE_NAME = upath.basename(__filename); - it(`should return an empty string when passed an error with no stack`, function() { + it(`should return an empty string when passed an error with no stack`, function () { const error = new Error(); error.stack = ''; expect(cleanupStackTrace(error, CURRENT_MODULE_NAME)).to.eql(''); }); - it(`should exclude every stack frame prior to the first frame of ${CURRENT_MODULE_NAME}`, function() { + it(`should exclude every stack frame prior to the first frame of ${CURRENT_MODULE_NAME}`, function () { const error = new Error(); const cleanStackTrace = cleanupStackTrace(error, CURRENT_MODULE_NAME); const frameCount = cleanStackTrace.split(`\n`).length; expect(frameCount).to.eql(1); }); - it(`should exclude every stack frame prior to the first frame of ${CURRENT_MODULE_NAME}, when the error is nested`, function() { + it(`should exclude every stack frame prior to the first frame of ${CURRENT_MODULE_NAME}, when the error is nested`, function () { let error; (() => { error = new Error(); @@ -37,11 +39,10 @@ describe(`[workbox-cli] lib/cleanup-stack-trace.js`, function() { expect(frameCount).to.eql(2); }); - it(`should exclude error.message, and just return the stack frames`, function() { + it(`should exclude error.message, and just return the stack frames`, function () { const error = new Error(`line 1\nline 2\nline 3`); const cleanStackTrace = cleanupStackTrace(error, CURRENT_MODULE_NAME); const frameCount = cleanStackTrace.split(`\n`).length; expect(frameCount).to.eql(1); }); }); - diff --git a/test/workbox-cli/node/lib/help-text.js b/test/workbox-cli/node/lib/help-text.js index 30c76254e..05a294a9d 100644 --- a/test/workbox-cli/node/lib/help-text.js +++ b/test/workbox-cli/node/lib/help-text.js @@ -8,10 +8,11 @@ const expect = require('chai').expect; -describe(`[workbox-cli] lib/help-text.js`, function() { - it(`should be a string`, function() { - const {helpText} = require('../../../../packages/workbox-cli/build/lib/help-text'); +describe(`[workbox-cli] lib/help-text.js`, function () { + it(`should be a string`, function () { + const { + helpText, + } = require('../../../../packages/workbox-cli/build/lib/help-text'); expect(helpText).to.be.a('string'); }); }); - diff --git a/test/workbox-cli/node/lib/logger.js b/test/workbox-cli/node/lib/logger.js index db246d24e..efb0d96f2 100644 --- a/test/workbox-cli/node/lib/logger.js +++ b/test/workbox-cli/node/lib/logger.js @@ -11,43 +11,42 @@ const sinon = require('sinon'); const {logger} = require('../../../../packages/workbox-cli/build/lib/logger'); -describe(`[workbox-cli] lib/logger.js`, function() { +describe(`[workbox-cli] lib/logger.js`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - it(`should call console.log() when logger.debug() is used`, function() { + it(`should call console.log() when logger.debug() is used`, function () { const stub = sandbox.stub(console, 'log'); logger.debug('Test'); sandbox.restore(); expect(stub.calledOnce).to.be.true; }); - it(`should call console.log() when logger.log() is used`, function() { + it(`should call console.log() when logger.log() is used`, function () { const stub = sandbox.stub(console, 'log'); logger.log('Test'); sandbox.restore(); expect(stub.calledOnce).to.be.true; }); - it(`should call console.warn() when logger.warn() is used`, function() { + it(`should call console.warn() when logger.warn() is used`, function () { const stub = sandbox.stub(console, 'warn'); logger.warn('Test'); sandbox.restore(); expect(stub.calledOnce).to.be.true; }); - it(`should call console.error() when logger.error() is used`, function() { + it(`should call console.error() when logger.error() is used`, function () { const stub = sandbox.stub(console, 'error'); logger.error('Test'); sandbox.restore(); expect(stub.calledOnce).to.be.true; }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-config-location.js b/test/workbox-cli/node/lib/questions/ask-config-location.js index 8a806c5ae..529c3e31f 100644 --- a/test/workbox-cli/node/lib/questions/ask-config-location.js +++ b/test/workbox-cli/node/lib/questions/ask-config-location.js @@ -9,15 +9,18 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../../packages/workbox-cli/build/lib/errors'); +const { + errors, +} = require('../../../../../packages/workbox-cli/build/lib/errors'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-config-location'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-config-location'; // This is the hardcoded name of the question that's passed to inquirer. // It's used as the key to read the response from the answer. const QUESTION_NAME = 'configLocation'; -describe(`[workbox-cli] lib/questions/ask-config-location.js`, function() { - it(`should reject with a 'invalid-config-location' error when the answer is an empty string`, async function() { +describe(`[workbox-cli] lib/questions/ask-config-location.js`, function () { + it(`should reject with a 'invalid-config-location' error when the answer is an empty string`, async function () { const {askConfigLocation} = proxyquire(MODULE_PATH, { inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: ''}), @@ -32,7 +35,7 @@ describe(`[workbox-cli] lib/questions/ask-config-location.js`, function() { } }); - it(`should resolve with the valid answer to the question`, async function() { + it(`should resolve with the valid answer to the question`, async function () { const expectedAnswer = 'expected answer'; const {askConfigLocation} = proxyquire(MODULE_PATH, { inquirer: { @@ -44,4 +47,3 @@ describe(`[workbox-cli] lib/questions/ask-config-location.js`, function() { expect(answer).to.eql(expectedAnswer); }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-extensions-to-cache.js b/test/workbox-cli/node/lib/questions/ask-extensions-to-cache.js index e75118904..fc8f1bafa 100644 --- a/test/workbox-cli/node/lib/questions/ask-extensions-to-cache.js +++ b/test/workbox-cli/node/lib/questions/ask-extensions-to-cache.js @@ -9,9 +9,12 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../../packages/workbox-cli/build/lib/errors'); +const { + errors, +} = require('../../../../../packages/workbox-cli/build/lib/errors'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-extensions-to-cache'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-extensions-to-cache'; // This is the hardcoded name of the question that's passed to inquirer. // It's used as the key to read the response from the answer. const QUESTION_NAME = 'globPatterns'; @@ -19,8 +22,8 @@ const GLOB_DIRECTORY = '/path/to/fake'; const SINGLE_EXTENSION = 'js'; const MULTIPLE_EXTENSIONS = ['html', 'js']; -describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { - it(`should reject with a 'no-file-extensions-found' error when the globDirectory doesn't contain any matching files`, async function() { +describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function () { + it(`should reject with a 'no-file-extensions-found' error when the globDirectory doesn't contain any matching files`, async function () { const {askExtensionsToCache} = proxyquire(MODULE_PATH, { glob: (pattern, config, callback) => { callback(null, []); @@ -42,7 +45,7 @@ describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { } }); - it(`should reject with a 'no-file-extensions-selected' error when the answer is an empty array`, async function() { + it(`should reject with a 'no-file-extensions-selected' error when the answer is an empty array`, async function () { const {askExtensionsToCache} = proxyquire(MODULE_PATH, { glob: (pattern, config, callback) => { callback(null, [`file.${SINGLE_EXTENSION}`]); @@ -67,7 +70,7 @@ describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { } }); - it(`should resolve with the expected value when the answer is a single extension`, async function() { + it(`should resolve with the expected value when the answer is a single extension`, async function () { const {askExtensionsToCache} = proxyquire(MODULE_PATH, { glob: (pattern, config, callback) => { callback(null, [`file.${SINGLE_EXTENSION}`]); @@ -88,10 +91,13 @@ describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { expect(answer).to.eql([`**/*.${SINGLE_EXTENSION}`]); }); - it(`should resolve with the expected value when the answer is multiple extensions`, async function() { + it(`should resolve with the expected value when the answer is multiple extensions`, async function () { const {askExtensionsToCache} = proxyquire(MODULE_PATH, { glob: (pattern, config, callback) => { - callback(null, MULTIPLE_EXTENSIONS.map((extension) => `file.${extension}`)); + callback( + null, + MULTIPLE_EXTENSIONS.map((extension) => `file.${extension}`), + ); }, inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: MULTIPLE_EXTENSIONS}), @@ -109,11 +115,14 @@ describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { expect(answer).to.eql([`**/*.{${MULTIPLE_EXTENSIONS.join(',')}}`]); }); - it(`should ignore the expected directories and extensions`, async function() { + it(`should ignore the expected directories and extensions`, async function () { const {askExtensionsToCache} = proxyquire(MODULE_PATH, { glob: (pattern, config, callback) => { expect(config.ignore).to.eql(['**/node_modules/**', '**/*.map']); - callback(null, MULTIPLE_EXTENSIONS.map((extension) => `file.${extension}`)); + callback( + null, + MULTIPLE_EXTENSIONS.map((extension) => `file.${extension}`), + ); }, inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: MULTIPLE_EXTENSIONS}), @@ -130,4 +139,3 @@ describe(`[workbox-cli] lib/questions/ask-extensions-to-cache.js`, function() { await askExtensionsToCache(GLOB_DIRECTORY); }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-questions.js b/test/workbox-cli/node/lib/questions/ask-questions.js index 2aebfed4b..fb39380d5 100644 --- a/test/workbox-cli/node/lib/questions/ask-questions.js +++ b/test/workbox-cli/node/lib/questions/ask-questions.js @@ -10,10 +10,11 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); const sinon = require('sinon'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-questions'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-questions'; -describe(`[workbox-cli] lib/questions/ask-questions.js`, function() { - it(`should ask all the expected questions in the correct order, and return the expected result in generateSW mode`, async function() { +describe(`[workbox-cli] lib/questions/ask-questions.js`, function () { + it(`should ask all the expected questions in the correct order, and return the expected result in generateSW mode`, async function () { // Using a stub that returns an increasing value for each call makes it // easy to verify that all the stubs are called in the expected order, // and to verify that the stub's responses are used to create the overall @@ -35,19 +36,26 @@ describe(`[workbox-cli] lib/questions/ask-questions.js`, function() { askConfigLocation: stub.callsFake(() => Promise.resolve(count++)), }, './ask-start_url-query-params': { - askQueryParametersInStartUrl: stub.callsFake(() => Promise.resolve(count++)), + askQueryParametersInStartUrl: stub.callsFake(() => + Promise.resolve(count++), + ), }, }); const answer = await askQuestions(); expect(answer).to.eql({ - config: {globDirectory: 0, globPatterns: 1, swDest: 2, ignoreURLParametersMatching: 4}, + config: { + globDirectory: 0, + globPatterns: 1, + swDest: 2, + ignoreURLParametersMatching: 4, + }, configLocation: 3, }); expect(stub.callCount).to.eql(5); }); - it(`should ask all the expected questions in the correct order, and return the expected result in injectManifest mode`, async function() { + it(`should ask all the expected questions in the correct order, and return the expected result in injectManifest mode`, async function () { // Using a stub that returns an increasing value for each call makes it // easy to verify that all the stubs are called in the expected order, // and to verify that the stub's responses are used to create the overall @@ -72,16 +80,23 @@ describe(`[workbox-cli] lib/questions/ask-questions.js`, function() { askConfigLocation: stub.callsFake(() => Promise.resolve(count++)), }, './ask-start_url-query-params': { - askQueryParametersInStartUrl: stub.callsFake(() => Promise.resolve(count++)), + askQueryParametersInStartUrl: stub.callsFake(() => + Promise.resolve(count++), + ), }, }); const answer = await askQuestions({injectManifest: true}); expect(answer).to.eql({ - config: {globDirectory: 0, globPatterns: 1, swSrc: 2, swDest: 3, ignoreURLParametersMatching: 5}, + config: { + globDirectory: 0, + globPatterns: 1, + swSrc: 2, + swDest: 3, + ignoreURLParametersMatching: 5, + }, configLocation: 4, }); expect(stub.callCount).to.eql(6); }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-root-of-web-app.js b/test/workbox-cli/node/lib/questions/ask-root-of-web-app.js index f5391700c..5dcf0b407 100644 --- a/test/workbox-cli/node/lib/questions/ask-root-of-web-app.js +++ b/test/workbox-cli/node/lib/questions/ask-root-of-web-app.js @@ -9,9 +9,12 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../../packages/workbox-cli/build/lib/errors'); +const { + errors, +} = require('../../../../../packages/workbox-cli/build/lib/errors'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-root-of-web-app'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-root-of-web-app'; // This is the hardcoded name of the question that's passed to inquirer. // It's used as the key to read the response from the answer. const questionRootDirectory = 'globDirectory'; @@ -21,8 +24,8 @@ const CHILD_DIRECTORY = '/path/to/directory/child'; const CHILD_DIRECTORY_WHITE_SPACE = '/path/to/directory/ child'; const CHILD_DIRECTORY_BLANK = ' '; -describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { - it(`should reject with a 'glob-directory-invalid' error when the answer isn't a valid directory`, async function() { +describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function () { + it(`should reject with a 'glob-directory-invalid' error when the answer isn't a valid directory`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); @@ -51,16 +54,17 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { } }); - it(`should reject with a 'glob-directory-invalid' error when the manual input is provided (directory does not exist)`, async function() { + it(`should reject with a 'glob-directory-invalid' error when the manual input is provided (directory does not exist)`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); }, 'inquirer': { - prompt: () => Promise.resolve({ - [questionRootDirectory]: DIRECTORY, - [questionManualInput]: CHILD_DIRECTORY, - }), + prompt: () => + Promise.resolve({ + [questionRootDirectory]: DIRECTORY, + [questionManualInput]: CHILD_DIRECTORY, + }), }, 'fs-extra': { stat: (path) => { @@ -81,7 +85,7 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { } }); - it(`should resolve with a valid answer to the question when no child directories are present (default: use current directory)`, async function() { + it(`should resolve with a valid answer to the question when no child directories are present (default: use current directory)`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); @@ -106,16 +110,17 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { expect(answer).to.eql(DIRECTORY); }); - it(`should resolve with a valid answer to the question when manual input is provided (directory exists)`, async function() { + it(`should resolve with a valid answer to the question when manual input is provided (directory exists)`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); }, 'inquirer': { - prompt: () => Promise.resolve({ - [questionRootDirectory]: DIRECTORY, - [questionManualInput]: CHILD_DIRECTORY, - }), + prompt: () => + Promise.resolve({ + [questionRootDirectory]: DIRECTORY, + [questionManualInput]: CHILD_DIRECTORY, + }), }, 'fs-extra': { stat: (path) => { @@ -132,16 +137,17 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { expect(answer).to.eql(CHILD_DIRECTORY); }); - it(`should resolve with a valid answer to the question when manual input is provided (directory exists and name contains white space)`, async function() { + it(`should resolve with a valid answer to the question when manual input is provided (directory exists and name contains white space)`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); }, 'inquirer': { - prompt: () => Promise.resolve({ - [questionRootDirectory]: DIRECTORY, - [questionManualInput]: CHILD_DIRECTORY_WHITE_SPACE, - }), + prompt: () => + Promise.resolve({ + [questionRootDirectory]: DIRECTORY, + [questionManualInput]: CHILD_DIRECTORY_WHITE_SPACE, + }), }, 'fs-extra': { stat: (path) => { @@ -158,16 +164,17 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { expect(answer).to.eql(CHILD_DIRECTORY_WHITE_SPACE); }); - it(`should resolve with a valid answer to the question when manual input is provided (directory exists and name is composed of only white space)`, async function() { + it(`should resolve with a valid answer to the question when manual input is provided (directory exists and name is composed of only white space)`, async function () { const {askRootOfWebApp} = proxyquire(MODULE_PATH, { 'glob': (pattern, config, callback) => { callback(null, []); }, 'inquirer': { - prompt: () => Promise.resolve({ - [questionRootDirectory]: DIRECTORY, - [questionManualInput]: CHILD_DIRECTORY_BLANK, - }), + prompt: () => + Promise.resolve({ + [questionRootDirectory]: DIRECTORY, + [questionManualInput]: CHILD_DIRECTORY_BLANK, + }), }, 'fs-extra': { stat: (path) => { @@ -184,4 +191,3 @@ describe(`[workbox-cli] lib/questions/ask-root-of-web-app.js`, function() { expect(answer).to.eql(CHILD_DIRECTORY_BLANK); }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-start_url-query-params.js b/test/workbox-cli/node/lib/questions/ask-start_url-query-params.js index 5dfc0303c..dd21ed80c 100644 --- a/test/workbox-cli/node/lib/questions/ask-start_url-query-params.js +++ b/test/workbox-cli/node/lib/questions/ask-start_url-query-params.js @@ -6,33 +6,40 @@ https://opensource.org/licenses/MIT. */ - const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../../packages/workbox-cli/build/lib/errors'); -const {constants} = require('../../../../../packages/workbox-cli/build/lib/constants'); +const { + errors, +} = require('../../../../../packages/workbox-cli/build/lib/errors'); +const { + constants, +} = require('../../../../../packages/workbox-cli/build/lib/constants'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-start_url-query-params'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-start_url-query-params'; // These are the hardcoded names of the question that are passed to inquirer. // They are used as the keys to read the response from the users answers. const question_ignoreURLParametersMatching = 'ignoreURLParametersMatching'; -const question_shouldAskForIgnoreURLParametersMatching = 'shouldAskForIgnoreURLParametersMatching'; +const question_shouldAskForIgnoreURLParametersMatching = + 'shouldAskForIgnoreURLParametersMatching'; const DEFAULT_IGNORED_URL_PARAMETERS = constants.ignoreURLParametersMatching; // Helper method for creating RegExp from dynamic values. const toRegex = (searchParam) => new RegExp(`^${searchParam}`); -describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() { - it(`should resolve with a default search parameters if answered no to the question`, async function() { +describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function () { + it(`should resolve with a default search parameters if answered no to the question`, async function () { const shouldAskForIgnoreURLParametersMatching = false; const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + }), }, }); @@ -40,13 +47,15 @@ describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() expect(answer).to.eql(DEFAULT_IGNORED_URL_PARAMETERS); }); - it(`should throw 'no-search-parameters-supplied' if answered yes and no url search parameters are passed`, async function() { + it(`should throw 'no-search-parameters-supplied' if answered yes and no url search parameters are passed`, async function () { const shouldAskForIgnoreURLParametersMatching = true; const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + }), }, }); @@ -58,15 +67,17 @@ describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() } }); - it(`should throw 'invalid-search-parameters-supplied' if url search parameter passed is prefixed with '?' or '/'`, async function() { + it(`should throw 'invalid-search-parameters-supplied' if url search parameter passed is prefixed with '?' or '/'`, async function () { const shouldAskForIgnoreURLParametersMatching = true; const ignoreURLParametersMatching = '?source'; const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, + }), }, }); @@ -74,19 +85,23 @@ describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() await askQueryParametersInStartUrl(); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.eql(errors['invalid-search-parameters-supplied']); + expect(error.message).to.eql( + errors['invalid-search-parameters-supplied'], + ); } }); - it(`should throw 'invalid-search-parameters-supplied' if one of the provided url search parameters is prefixed with '?' or '/'`, async function() { + it(`should throw 'invalid-search-parameters-supplied' if one of the provided url search parameters is prefixed with '?' or '/'`, async function () { const shouldAskForIgnoreURLParametersMatching = true; const ignoreURLParametersMatching = 'search,version,?language'; const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, + }), }, }); @@ -94,20 +109,26 @@ describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() await askQueryParametersInStartUrl(); throw new Error('Unexpected success.'); } catch (error) { - expect(error.message).to.eql(errors['invalid-search-parameters-supplied']); + expect(error.message).to.eql( + errors['invalid-search-parameters-supplied'], + ); } }); - it(`should resolve with a list of search parameters when a valid url search parameter is passed`, async function() { + it(`should resolve with a list of search parameters when a valid url search parameter is passed`, async function () { const shouldAskForIgnoreURLParametersMatching = true; const ignoreURLParametersMatching = 'search'; - const expectedAnswer = DEFAULT_IGNORED_URL_PARAMETERS.concat(toRegex(ignoreURLParametersMatching)); + const expectedAnswer = DEFAULT_IGNORED_URL_PARAMETERS.concat( + toRegex(ignoreURLParametersMatching), + ); const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, + }), }, }); @@ -115,16 +136,20 @@ describe(`[workbox-cli] lib/questions/ask-start_url-query-params.js`, function() expect(answer).to.eql(expectedAnswer); }); - it(`should resolve with a list of search parameters when a valid list of url search parameters is passed`, async function() { + it(`should resolve with a list of search parameters when a valid list of url search parameters is passed`, async function () { const shouldAskForIgnoreURLParametersMatching = true; const ignoreURLParametersMatching = 'search,version,language'; - const expectedAnswer = DEFAULT_IGNORED_URL_PARAMETERS.concat(ignoreURLParametersMatching.split(',').map(toRegex)); + const expectedAnswer = DEFAULT_IGNORED_URL_PARAMETERS.concat( + ignoreURLParametersMatching.split(',').map(toRegex), + ); const {askQueryParametersInStartUrl} = proxyquire(MODULE_PATH, { - 'inquirer': { - prompt: () => Promise.resolve({ - [question_shouldAskForIgnoreURLParametersMatching]: shouldAskForIgnoreURLParametersMatching, - [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, - }), + inquirer: { + prompt: () => + Promise.resolve({ + [question_shouldAskForIgnoreURLParametersMatching]: + shouldAskForIgnoreURLParametersMatching, + [question_ignoreURLParametersMatching]: ignoreURLParametersMatching, + }), }, }); diff --git a/test/workbox-cli/node/lib/questions/ask-sw-dest.js b/test/workbox-cli/node/lib/questions/ask-sw-dest.js index 19d11ab71..6f14cca72 100644 --- a/test/workbox-cli/node/lib/questions/ask-sw-dest.js +++ b/test/workbox-cli/node/lib/questions/ask-sw-dest.js @@ -9,17 +9,20 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const {errors} = require('../../../../../packages/workbox-cli/build/lib/errors'); +const { + errors, +} = require('../../../../../packages/workbox-cli/build/lib/errors'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-sw-dest'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-sw-dest'; // This is the hardcoded name of the question that's passed to inquirer. // It's used as the key to read the response from the answer. const QUESTION_NAME = 'swDest'; -describe(`[workbox-cli] lib/questions/ask-sw-dest.js`, function() { - it(`should reject with a 'invalid-sw-dest' error when the answer is empty`, async function() { +describe(`[workbox-cli] lib/questions/ask-sw-dest.js`, function () { + it(`should reject with a 'invalid-sw-dest' error when the answer is empty`, async function () { const {askSWDest} = proxyquire(MODULE_PATH, { - 'inquirer': { + inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: ''}), }, }); @@ -32,10 +35,10 @@ describe(`[workbox-cli] lib/questions/ask-sw-dest.js`, function() { } }); - it(`should reject with a valid answer to the question`, async function() { + it(`should reject with a valid answer to the question`, async function () { const expectedAnswer = 'expected answer'; const {askSWDest} = proxyquire(MODULE_PATH, { - 'inquirer': { + inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: expectedAnswer}), }, }); @@ -44,4 +47,3 @@ describe(`[workbox-cli] lib/questions/ask-sw-dest.js`, function() { expect(answer).to.eql(expectedAnswer); }); }); - diff --git a/test/workbox-cli/node/lib/questions/ask-sw-src.js b/test/workbox-cli/node/lib/questions/ask-sw-src.js index ef1f587fb..c302272fb 100644 --- a/test/workbox-cli/node/lib/questions/ask-sw-src.js +++ b/test/workbox-cli/node/lib/questions/ask-sw-src.js @@ -9,16 +9,17 @@ const expect = require('chai').expect; const proxyquire = require('proxyquire'); -const MODULE_PATH = '../../../../../packages/workbox-cli/build/lib/questions/ask-sw-src'; +const MODULE_PATH = + '../../../../../packages/workbox-cli/build/lib/questions/ask-sw-src'; // This is the hardcoded name of the question that's passed to inquirer. // It's used as the key to read the response from the answer. const QUESTION_NAME = 'swSrc'; -describe(`[workbox-cli] lib/questions/ask-sw-src.js`, function() { - it(`should resolve with a valid answer to the question`, async function() { +describe(`[workbox-cli] lib/questions/ask-sw-src.js`, function () { + it(`should resolve with a valid answer to the question`, async function () { const expectedAnswer = 'expected answer'; const {askSWSrc} = proxyquire(MODULE_PATH, { - 'inquirer': { + inquirer: { prompt: () => Promise.resolve({[QUESTION_NAME]: expectedAnswer}), }, }); @@ -27,4 +28,3 @@ describe(`[workbox-cli] lib/questions/ask-sw-src.js`, function() { expect(answer).to.eql(expectedAnswer); }); }); - diff --git a/test/workbox-cli/node/lib/run-wizard.js b/test/workbox-cli/node/lib/run-wizard.js index 440a61230..b9d530704 100644 --- a/test/workbox-cli/node/lib/run-wizard.js +++ b/test/workbox-cli/node/lib/run-wizard.js @@ -13,8 +13,8 @@ const sinon = require('sinon'); const MODULE_PATH = '../../../../packages/workbox-cli/build/lib/run-wizard'; -describe(`[workbox-cli] lib/run-wizard.js`, function() { - it(`should write the configuration to the expected location based on the answers provided`, async function() { +describe(`[workbox-cli] lib/run-wizard.js`, function () { + it(`should write the configuration to the expected location based on the answers provided`, async function () { const configLocation = upath.join('path', 'to', 'config.js'); const config = {dummy: 123, regExp: [/1/, /2/]}; const fseWriteFileStub = sinon.stub().resolves(); @@ -41,7 +41,7 @@ describe(`[workbox-cli] lib/run-wizard.js`, function() { expect(fseArgs[0]).to.eql(configLocation); // See https://github.com/GoogleChrome/workbox/issues/2796 expect(fseArgs[1]).to.eql( - `module.exports = { + `module.exports = { \tdummy: 123, \tregExp: [ \t\t/1/, @@ -52,4 +52,3 @@ describe(`[workbox-cli] lib/run-wizard.js`, function() { expect(loggerStub.calledTwice).to.be.true; }); }); - diff --git a/test/workbox-core/integration/test-all.js b/test/workbox-core/integration/test-all.js index 7a41fb4d8..43594a1dd 100644 --- a/test/workbox-core/integration/test-all.js +++ b/test/workbox-core/integration/test-all.js @@ -9,22 +9,21 @@ const activateAndControlSW = require('../../../infra/testing/activate-and-control'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-core]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-core]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-core/sw/'); }); }); -describe(`[workbox-core] Load core in the browser`, function() { +describe(`[workbox-core] Load core in the browser`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-core/static/core-in-browser/`; const swURL = `${testingURL}sw.js`; - it(`should load workbox-core in a service worker.`, async function() { + it(`should load workbox-core in a service worker.`, async function () { await webdriver.get(testingURL); await activateAndControlSW(swURL); diff --git a/test/workbox-core/static/core-in-browser/index.html b/test/workbox-core/static/core-in-browser/index.html index af5352629..6a0e79857 100644 --- a/test/workbox-core/static/core-in-browser/index.html +++ b/test/workbox-core/static/core-in-browser/index.html @@ -1,6 +1,5 @@ - - +

    You need to manually register sw.js

    @@ -8,4 +7,4 @@ window.__test = {}; - + diff --git a/test/workbox-core/static/logger.html b/test/workbox-core/static/logger.html index 64452e8a5..a3965c021 100644 --- a/test/workbox-core/static/logger.html +++ b/test/workbox-core/static/logger.html @@ -1,107 +1,110 @@ - - - -

    IMPORTANT: Chrome DevTools recently changed to hide console.debug logs, so - if you do the debug logs, please check DevTools is set to show all levels. -

    -

    Current Log Level: ""

    -

    logger.*()

    - - - - - + + + +

    + IMPORTANT: Chrome DevTools recently changed to hide console.debug logs, so + if you do the debug logs, please check DevTools is set to show all levels. +

    +

    Current Log Level: ""

    +

    logger.*()

    + + + + + - + - - + - + console.log('\n\n'); + }); + + diff --git a/test/workbox-core/sw/_private/test-Deferred.mjs b/test/workbox-core/sw/_private/test-Deferred.mjs index 8aacaa0c9..ae7c7f02e 100644 --- a/test/workbox-core/sw/_private/test-Deferred.mjs +++ b/test/workbox-core/sw/_private/test-Deferred.mjs @@ -8,16 +8,15 @@ import {Deferred} from 'workbox-core/_private/Deferred.mjs'; - -describe(`Deferred`, function() { - describe(`constructor`, function() { - it(`should create a promise and expose its resolve and reject functions as methods`, function() { +describe(`Deferred`, function () { + describe(`constructor`, function () { + it(`should create a promise and expose its resolve and reject functions as methods`, function () { expect(new Deferred().promise).to.be.an.instanceof(Promise); }); }); - describe(`resolve`, function() { - it(`should resolve the Deferred's promise`, function() { + describe(`resolve`, function () { + it(`should resolve the Deferred's promise`, function () { const deferred = new Deferred(); deferred.resolve(); @@ -25,8 +24,8 @@ describe(`Deferred`, function() { }); }); - describe(`reject`, function() { - it(`should reject the Deferred's promise with the passed error`, function(done) { + describe(`reject`, function () { + it(`should reject the Deferred's promise with the passed error`, function (done) { const deferred = new Deferred(); const err1 = new Error('1'); deferred.reject(err1); diff --git a/test/workbox-core/sw/_private/test-assert.mjs b/test/workbox-core/sw/_private/test-assert.mjs index bd7a61ceb..805dcb4de 100644 --- a/test/workbox-core/sw/_private/test-assert.mjs +++ b/test/workbox-core/sw/_private/test-assert.mjs @@ -8,16 +8,15 @@ import {assert} from 'workbox-core/_private/assert'; - -describe(`assert`, function() { - it(`should be null in production mode`, function() { +describe(`assert`, function () { + it(`should be null in production mode`, function () { if (process.env.NODE_ENV === 'production') { expect(assert).to.equal(null); } }); - describe(`isArray`, function() { - it(`shouldn't throw when given an array`, function() { + describe(`isArray`, function () { + it(`shouldn't throw when given an array`, function () { if (process.env.NODE_ENV === 'production') this.skip(); assert.isArray([], { @@ -28,49 +27,60 @@ describe(`assert`, function() { }); }); - it(`should throw when value isn't an array`, function() { + it(`should throw when value isn't an array`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { - assert.isArray({}, { - moduleName: 'module', - className: 'class', - funcName: 'func', - paramName: 'param', - }); + assert.isArray( + {}, + { + moduleName: 'module', + className: 'class', + funcName: 'func', + paramName: 'param', + }, + ); }, 'not-an-array'); }); }); - describe(`isArrayOfClass`, function() { - it(`shouldn't throw when given an array same Class`, function() { + describe(`isArrayOfClass`, function () { + it(`shouldn't throw when given an array same Class`, function () { if (process.env.NODE_ENV === 'production') this.skip(); class TestClass {} - assert.isArrayOfClass([new TestClass(), new TestClass(), new TestClass()], TestClass, { - moduleName: 'module', - className: 'class', - funcName: 'func', - paramName: 'param', - }); + assert.isArrayOfClass( + [new TestClass(), new TestClass(), new TestClass()], + TestClass, + { + moduleName: 'module', + className: 'class', + funcName: 'func', + paramName: 'param', + }, + ); }); - it(`should throw when value isn't an array of Class`, function() { + it(`should throw when value isn't an array of Class`, function () { if (process.env.NODE_ENV === 'production') this.skip(); class TestClass {} class NotTestClass {} return expectError(() => { - assert.isArrayOfClass([new TestClass(), new NotTestClass(), new TestClass()], TestClass, { - moduleName: 'module', - className: 'class', - funcName: 'func', - paramName: 'param', - }); + assert.isArrayOfClass( + [new TestClass(), new NotTestClass(), new TestClass()], + TestClass, + { + moduleName: 'module', + className: 'class', + funcName: 'func', + paramName: 'param', + }, + ); }, 'not-array-of-class'); }); - it(`should throw when value isn't an array`, function() { + it(`should throw when value isn't an array`, function () { if (process.env.NODE_ENV === 'production') this.skip(); class TestClass {} @@ -85,8 +95,8 @@ describe(`assert`, function() { }); }); - describe(`hasMethod`, function() { - it(`should throw when it has no method`, function() { + describe(`hasMethod`, function () { + it(`should throw when it has no method`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -99,7 +109,7 @@ describe(`assert`, function() { }, 'missing-a-method'); }); - it(`should throw when it has no method`, function() { + it(`should throw when it has no method`, function () { if (process.env.NODE_ENV === 'production') this.skip(); assert.hasMethod({methodName: () => {}}, 'methodName', { @@ -111,8 +121,8 @@ describe(`assert`, function() { }); }); - describe(`isInstance`, function() { - it(`should throw when it is not an instance`, function() { + describe(`isInstance`, function () { + it(`should throw when it is not an instance`, function () { if (process.env.NODE_ENV === 'production') this.skip(); class Example {} @@ -126,7 +136,7 @@ describe(`assert`, function() { }, 'incorrect-class'); }); - it(`should not throw when it is an instance`, function() { + it(`should not throw when it is an instance`, function () { if (process.env.NODE_ENV === 'production') this.skip(); class Example {} @@ -139,8 +149,8 @@ describe(`assert`, function() { }); }); - describe(`isOneOf`, function() { - it(`should throw when it is not an instance`, function() { + describe(`isOneOf`, function () { + it(`should throw when it is not an instance`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -153,7 +163,7 @@ describe(`assert`, function() { }, 'invalid-value'); }); - it(`should throw when it is not an instance`, function() { + it(`should throw when it is not an instance`, function () { if (process.env.NODE_ENV === 'production') this.skip(); assert.isOneOf('ok-value', ['ok-value'], { diff --git a/test/workbox-core/sw/_private/test-cacheMatchIgnoreParams.mjs b/test/workbox-core/sw/_private/test-cacheMatchIgnoreParams.mjs index 8741a175d..ce52cdd9f 100644 --- a/test/workbox-core/sw/_private/test-cacheMatchIgnoreParams.mjs +++ b/test/workbox-core/sw/_private/test-cacheMatchIgnoreParams.mjs @@ -8,8 +8,7 @@ import {cacheMatchIgnoreParams} from 'workbox-core/_private/cacheMatchIgnoreParams.mjs'; - -describe(`cacheMatchIgnoreParams()`, function() { +describe(`cacheMatchIgnoreParams()`, function () { const sandbox = sinon.createSandbox(); let cache; const urls = [ @@ -23,7 +22,7 @@ describe(`cacheMatchIgnoreParams()`, function() { '/two?a=1&b=2&c=3', ]; - beforeEach(async function() { + beforeEach(async function () { await caches.delete('test'); cache = await caches.open('test'); @@ -33,13 +32,13 @@ describe(`cacheMatchIgnoreParams()`, function() { sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - it(`matches items in the cache ignoring the passed param(s)`, async function() { + it(`matches items in the cache ignoring the passed param(s)`, async function () { const key1 = new Request('/one?a=MISS&b=2'); const match1 = await cacheMatchIgnoreParams(cache, key1, ['a']); expect(await match1.text()).to.equal('/one?a=1&b=2'); @@ -53,7 +52,7 @@ describe(`cacheMatchIgnoreParams()`, function() { expect(await match3.text()).to.equal('/one?a=1'); }); - it(`matches the first item if there's more than one match`, async function() { + it(`matches the first item if there's more than one match`, async function () { const key = new Request('/two?a=1&b=2&c=MISS'); const match = await cacheMatchIgnoreParams(cache, key, ['c']); @@ -62,7 +61,7 @@ describe(`cacheMatchIgnoreParams()`, function() { expect(await match.text()).to.equal('/two?a=1&b=2'); }); - it(`matches as normal if the param is not present`, async function() { + it(`matches as normal if the param is not present`, async function () { const key = new Request('/two'); const match1 = await cacheMatchIgnoreParams(cache, key, ['c']); @@ -72,7 +71,7 @@ describe(`cacheMatchIgnoreParams()`, function() { expect(await match2.text()).to.equal('/two'); }); - it(`returns undefined if no match is found`, async function() { + it(`returns undefined if no match is found`, async function () { const key = new Request('/two?a=MISS&b=2'); const match = await cacheMatchIgnoreParams(cache, key, ['b']); expect(match).to.equal(undefined); diff --git a/test/workbox-core/sw/_private/test-executeQuotaErrorCallbacks.mjs b/test/workbox-core/sw/_private/test-executeQuotaErrorCallbacks.mjs index faa44a3ec..dcd4e3fd1 100644 --- a/test/workbox-core/sw/_private/test-executeQuotaErrorCallbacks.mjs +++ b/test/workbox-core/sw/_private/test-executeQuotaErrorCallbacks.mjs @@ -9,15 +9,14 @@ import {executeQuotaErrorCallbacks} from 'workbox-core/_private/executeQuotaErrorCallbacks.mjs'; import {registerQuotaErrorCallback} from 'workbox-core/registerQuotaErrorCallback.mjs'; - -describe(`executeQuotaErrorCallbacks()`, function() { +describe(`executeQuotaErrorCallbacks()`, function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it('should call everything registered with registerQuotaErrorCallback()', async function() { + it('should call everything registered with registerQuotaErrorCallback()', async function () { const callback1 = sandbox.stub(); registerQuotaErrorCallback(callback1); const callback2 = sandbox.stub(); @@ -29,7 +28,7 @@ describe(`executeQuotaErrorCallbacks()`, function() { expect(callback2.calledOnce).to.be.true; }); - it(`shouldn't have any effect if called multiple times with the same callback`, async function() { + it(`shouldn't have any effect if called multiple times with the same callback`, async function () { const callback1 = sandbox.stub(); registerQuotaErrorCallback(callback1); registerQuotaErrorCallback(callback1); @@ -40,7 +39,7 @@ describe(`executeQuotaErrorCallbacks()`, function() { expect(callback1.calledOnce).to.be.true; }); - it(`should call everything registered with registerQuotaErrorCallback(), each time it's called`, async function() { + it(`should call everything registered with registerQuotaErrorCallback(), each time it's called`, async function () { const callback1 = sandbox.stub(); registerQuotaErrorCallback(callback1); const callback2 = sandbox.stub(); diff --git a/test/workbox-core/sw/_private/test-getFriendlyURL.mjs b/test/workbox-core/sw/_private/test-getFriendlyURL.mjs index 65dcc66e0..76fa0e2fb 100644 --- a/test/workbox-core/sw/_private/test-getFriendlyURL.mjs +++ b/test/workbox-core/sw/_private/test-getFriendlyURL.mjs @@ -8,38 +8,37 @@ import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs'; - -describe(`getFriendlyURL()`, function() { - it(`should return short URL for local origin '/'`, function() { +describe(`getFriendlyURL()`, function () { + it(`should return short URL for local origin '/'`, function () { const url = getFriendlyURL('/'); expect(url).to.equal('/'); }); - it(`should return short URL for local origin '/hi'`, function() { + it(`should return short URL for local origin '/hi'`, function () { const fullURL = new URL('/hi', self.location).toString(); const url = getFriendlyURL(fullURL); expect(url).to.equal('/hi'); }); - it(`should include the URL's hash in the returned string`, function() { + it(`should include the URL's hash in the returned string`, function () { const fullURL = new URL('/hi#test', self.location).toString(); const url = getFriendlyURL(fullURL); expect(url).to.equal('/hi#test'); }); - it(`should include the URL's search in the returned string`, function() { + it(`should include the URL's search in the returned string`, function () { const fullURL = new URL('/hi?one=two', self.location).toString(); const url = getFriendlyURL(fullURL); expect(url).to.equal('/hi?one=two'); }); - it(`should include the URL's search and hash in the returned string`, function() { + it(`should include the URL's search and hash in the returned string`, function () { const fullURL = new URL('/hi?one=two#test', self.location).toString(); const url = getFriendlyURL(fullURL); expect(url).to.equal('/hi?one=two#test'); }); - it(`should return full URL for external origin 'https://external-example.com/example'`, function() { + it(`should return full URL for external origin 'https://external-example.com/example'`, function () { const url = getFriendlyURL('https://external-example.com/example'); expect(url).to.equal('https://external-example.com/example'); }); diff --git a/test/workbox-core/sw/_private/test-logger.mjs b/test/workbox-core/sw/_private/test-logger.mjs index c0c9a7dfb..5593fc10e 100644 --- a/test/workbox-core/sw/_private/test-logger.mjs +++ b/test/workbox-core/sw/_private/test-logger.mjs @@ -8,13 +8,13 @@ import {logger} from 'workbox-core/_private/logger.mjs'; -describe(`logger`, function() { +describe(`logger`, function () { const SAFARI_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15`; const CHROME_USER_AGENT = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36`; const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); // Undo the logger stubs setup in infra/testing/auto-stub-logger.mjs @@ -30,16 +30,11 @@ describe(`logger`, function() { self.__WB_DISABLE_DEV_LOGS = false; }); - after(function() { + after(function () { sandbox.restore(); }); - const consoleLevels = [ - 'debug', - 'log', - 'warn', - 'error', - ]; + const consoleLevels = ['debug', 'log', 'warn', 'error']; const validateStub = (stub, expectedArgs, isPrefixed) => { expect(stub.callCount).to.equal(1); @@ -55,13 +50,13 @@ describe(`logger`, function() { expect(calledArgs).to.deep.equal(expectedArgs); }; - it(`should be null in production mode`, function() { + it(`should be null in production mode`, function () { if (process.env.NODE_ENV !== 'production') this.skip(); expect(logger).to.equal(null); }); - it(`should toggle logging based on the value of __WB_DISABLE_DEV_LOGS`, function() { + it(`should toggle logging based on the value of __WB_DISABLE_DEV_LOGS`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const logStub = sandbox.stub(console, 'log'); @@ -76,8 +71,8 @@ describe(`logger`, function() { }); consoleLevels.forEach((consoleLevel) => { - describe(`.${consoleLevel}()`, function() { - it(`should work without input`, function() { + describe(`.${consoleLevel}()`, function () { + it(`should work without input`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const stub = sandbox.stub(console, consoleLevel); @@ -90,7 +85,7 @@ describe(`logger`, function() { validateStub(stub, [], true); }); - it(`should work with several inputs`, function() { + it(`should work with several inputs`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const stub = sandbox.stub(console, consoleLevel); @@ -106,8 +101,8 @@ describe(`logger`, function() { }); }); - describe(`.groupCollapsed()`, function() { - it(`should work without input`, function() { + describe(`.groupCollapsed()`, function () { + it(`should work without input`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const stub = sandbox.stub(console, 'groupCollapsed'); @@ -125,8 +120,11 @@ describe(`logger`, function() { // There's User-Agent sniffing in the logger code, so we need to run // two different test scenarios for Safari and non-Safari browsers. // See https://github.com/GoogleChrome/workbox/issues/2149 - for (const [userAgent, isPrefixed] of new Map([[SAFARI_USER_AGENT, false], [CHROME_USER_AGENT, true]])) { - it(`should work with several inputs (for ${userAgent})`, function() { + for (const [userAgent, isPrefixed] of new Map([ + [SAFARI_USER_AGENT, false], + [CHROME_USER_AGENT, true], + ])) { + it(`should work with several inputs (for ${userAgent})`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const stub = sandbox.stub(console, 'groupCollapsed'); @@ -143,7 +141,7 @@ describe(`logger`, function() { validateStub(stub, args, isPrefixed); }); - it(`should not prefix log message until after .groupEnd() is called (for ${userAgent})`, function() { + it(`should not prefix log message until after .groupEnd() is called (for ${userAgent})`, function () { if (process.env.NODE_ENV === 'production') this.skip(); sandbox.replaceGetter(navigator, 'userAgent', () => userAgent); @@ -183,8 +181,8 @@ describe(`logger`, function() { } }); - describe(`.groupEnd()`, function() { - it(`should work without input`, function() { + describe(`.groupEnd()`, function () { + it(`should work without input`, function () { if (process.env.NODE_ENV === 'production') this.skip(); const stub = sandbox.stub(console, 'groupEnd'); diff --git a/test/workbox-core/sw/_private/test-resultingClientExists.mjs b/test/workbox-core/sw/_private/test-resultingClientExists.mjs index a65ffaaff..10fddb93e 100644 --- a/test/workbox-core/sw/_private/test-resultingClientExists.mjs +++ b/test/workbox-core/sw/_private/test-resultingClientExists.mjs @@ -8,33 +8,40 @@ import {resultingClientExists} from 'workbox-core/_private/resultingClientExists.mjs'; - -describe(`resultingClientExists()`, function() { +describe(`resultingClientExists()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should resolve to a matching window client ID`, async function() { - sandbox.stub(clients, 'matchAll') - .onFirstCall().resolves([{id: '1'}, {id: '2'}]) - .onSecondCall().resolves([{id: '1'}, {id: '2'}]) - .onThirdCall().resolves([{id: '1'}, {id: '3'}]); + it(`should resolve to a matching window client ID`, async function () { + sandbox + .stub(clients, 'matchAll') + .onFirstCall() + .resolves([{id: '1'}, {id: '2'}]) + .onSecondCall() + .resolves([{id: '1'}, {id: '2'}]) + .onThirdCall() + .resolves([{id: '1'}, {id: '3'}]); const win = await resultingClientExists('3'); expect(win.id).to.equal('3'); }); - it(`should resolve to undefined when not passed a value`, async function() { - sandbox.stub(clients, 'matchAll') - .onFirstCall().resolves([{id: '1'}, {id: '2'}]) - .onSecondCall().resolves([{id: '1'}, {id: '2'}]) - .onThirdCall().resolves([{id: '1'}, {id: '3'}]); + it(`should resolve to undefined when not passed a value`, async function () { + sandbox + .stub(clients, 'matchAll') + .onFirstCall() + .resolves([{id: '1'}, {id: '2'}]) + .onSecondCall() + .resolves([{id: '1'}, {id: '2'}]) + .onThirdCall() + .resolves([{id: '1'}, {id: '3'}]); const startTime = performance.now(); const win = await resultingClientExists(); @@ -43,7 +50,7 @@ describe(`resultingClientExists()`, function() { expect(performance.now() - startTime).to.be.below(2000); }); - it(`should resolve to undefined after 2 seconds of unsuccessful retrying`, async function() { + it(`should resolve to undefined after 2 seconds of unsuccessful retrying`, async function () { sandbox.stub(clients, 'matchAll').resolves([{id: '1'}, {id: '2'}]); const startTime = performance.now(); diff --git a/test/workbox-core/sw/_private/test-timeout.mjs b/test/workbox-core/sw/_private/test-timeout.mjs index 8fed21a7a..9edb6e8ff 100644 --- a/test/workbox-core/sw/_private/test-timeout.mjs +++ b/test/workbox-core/sw/_private/test-timeout.mjs @@ -8,19 +8,18 @@ import {timeout} from 'workbox-core/_private/timeout.mjs'; - -describe(`timeout()`, function() { +describe(`timeout()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should return a promise that resolves after the passed number of milliseconds`, function(done) { + it(`should return a promise that resolves after the passed number of milliseconds`, function (done) { const clock = sandbox.useFakeTimers(); const startTime = performance.now(); diff --git a/test/workbox-core/sw/_private/test-waitUntil.mjs b/test/workbox-core/sw/_private/test-waitUntil.mjs index 520953fa4..6aa6e6fcc 100644 --- a/test/workbox-core/sw/_private/test-waitUntil.mjs +++ b/test/workbox-core/sw/_private/test-waitUntil.mjs @@ -9,19 +9,18 @@ import {waitUntil} from 'workbox-core/_private/waitUntil.mjs'; import {spyOnEvent} from '../../../../infra/testing/helpers/extendable-event-utils.mjs'; - -describe(`waitUntil()`, function() { +describe(`waitUntil()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); }); - after(async function() { + after(async function () { sandbox.restore(); }); - it(`adds an async function's returned promise to an event and returns it`, async function() { + it(`adds an async function's returned promise to an event and returns it`, async function () { const event = new ExtendableEvent('install'); spyOnEvent(event); diff --git a/test/workbox-core/sw/models/messages/test-messageGenerator.mjs b/test/workbox-core/sw/models/messages/test-messageGenerator.mjs index d95cdce85..30024c802 100644 --- a/test/workbox-core/sw/models/messages/test-messageGenerator.mjs +++ b/test/workbox-core/sw/models/messages/test-messageGenerator.mjs @@ -8,14 +8,13 @@ import {messageGenerator} from 'workbox-core/models/messages/messageGenerator.mjs'; - -describe(`messageGenerator`, function() { +describe(`messageGenerator`, function () { const detailsObj = { exampleDetail: 'With Value', }; const detailsString = `${JSON.stringify([detailsObj])}`; - it(`should handle unknown codes`, function() { + it(`should handle unknown codes`, function () { if (process.env.NODE_ENV === 'production') { const message = messageGenerator('fake-code'); @@ -27,7 +26,7 @@ describe(`messageGenerator`, function() { } }); - it(`should return the code with details if the code is unknown`, function() { + it(`should return the code with details if the code is unknown`, function () { if (process.env.NODE_ENV === 'production') { const message = messageGenerator('fake-code', detailsObj); expect(message).to.equal(`fake-code :: ${detailsString}`); @@ -38,7 +37,7 @@ describe(`messageGenerator`, function() { } }); - it(`should throw an error if the code is valid but no required details are defined`, function() { + it(`should throw an error if the code is valid but no required details are defined`, function () { if (process.env.NODE_ENV === 'production') { const message = messageGenerator('incorrect-type'); expect(message).to.equal(`incorrect-type`); @@ -49,7 +48,7 @@ describe(`messageGenerator`, function() { } }); - it(`should throw an error if the code is valid but the arguments are missing details`, function() { + it(`should throw an error if the code is valid but the arguments are missing details`, function () { if (process.env.NODE_ENV === 'production') { const message = messageGenerator('incorrect-type', detailsObj); expect(message).to.equal(`incorrect-type :: ${detailsString}`); @@ -60,7 +59,7 @@ describe(`messageGenerator`, function() { } }); - it(`should return the message if the code and details are valid`, function() { + it(`should return the message if the code and details are valid`, function () { const invalidTypeDetails = { moduleName: 'test', className: 'test', @@ -71,7 +70,9 @@ describe(`messageGenerator`, function() { const message = messageGenerator('incorrect-type', invalidTypeDetails); if (process.env.NODE_ENV === 'production') { - expect(message).to.equal(`incorrect-type :: ${JSON.stringify([invalidTypeDetails])}`); + expect(message).to.equal( + `incorrect-type :: ${JSON.stringify([invalidTypeDetails])}`, + ); } else { expect(message.indexOf('incorrect-type')).to.equal(-1); } diff --git a/test/workbox-core/sw/test-cacheNames.mjs b/test/workbox-core/sw/test-cacheNames.mjs index e76417bb6..513a7a39f 100644 --- a/test/workbox-core/sw/test-cacheNames.mjs +++ b/test/workbox-core/sw/test-cacheNames.mjs @@ -10,9 +10,8 @@ import {cacheNames} from 'workbox-core/cacheNames.mjs'; import {setCacheNameDetails} from 'workbox-core/setCacheNameDetails.mjs'; import generateVariantTests from '../../../infra/testing/generate-variant-tests'; - -describe(`cacheNames`, function() { - afterEach(function() { +describe(`cacheNames`, function () { + afterEach(function () { // TODO(gauntface): there should be a way to get access to the current // (or default) prefix and suffix values so they can be restored here. setCacheNameDetails({ @@ -24,24 +23,32 @@ describe(`cacheNames`, function() { }); }); - it('should return expected defaults', function() { + it('should return expected defaults', function () { // Scope be default is '/' from 'service-worker-mock' - expect(cacheNames.precache).to.equal(`workbox-precache-v2-${self.registration.scope}`); - expect(cacheNames.runtime).to.equal(`workbox-runtime-${self.registration.scope}`); + expect(cacheNames.precache).to.equal( + `workbox-precache-v2-${self.registration.scope}`, + ); + expect(cacheNames.runtime).to.equal( + `workbox-runtime-${self.registration.scope}`, + ); expect(cacheNames.prefix).to.equal('workbox'); expect(cacheNames.suffix).to.equal(self.registration.scope); }); - it('should allow customising the prefix', function() { + it('should allow customising the prefix', function () { setCacheNameDetails({prefix: 'test-prefix'}); // Scope by default is '/' from 'service-worker-mock' - expect(cacheNames.precache).to.equal(`test-prefix-precache-${self.registration.scope}`); - expect(cacheNames.runtime).to.equal(`test-prefix-runtime-${self.registration.scope}`); + expect(cacheNames.precache).to.equal( + `test-prefix-precache-${self.registration.scope}`, + ); + expect(cacheNames.runtime).to.equal( + `test-prefix-runtime-${self.registration.scope}`, + ); expect(cacheNames.prefix).to.equal('test-prefix'); }); - it('should allow customising the suffix', function() { + it('should allow customising the suffix', function () { setCacheNameDetails({suffix: 'test-suffix'}); // Scope be default is '/' from 'service-worker-mock' @@ -50,30 +57,37 @@ describe(`cacheNames`, function() { expect(cacheNames.suffix).to.equal('test-suffix'); }); - - it('should allow customising the precache name', function() { + it('should allow customising the precache name', function () { setCacheNameDetails({precache: 'test-precache'}); // Scope be default is '/' from 'service-worker-mock' - expect(cacheNames.precache).to.equal(`workbox-test-precache-${self.registration.scope}`); + expect(cacheNames.precache).to.equal( + `workbox-test-precache-${self.registration.scope}`, + ); }); - it('should allow customising the runtime name', function() { + it('should allow customising the runtime name', function () { setCacheNameDetails({runtime: 'test-runtime'}); // Scope be default is '/' from 'service-worker-mock' - expect(cacheNames.precache).to.equal(`workbox-precache-${self.registration.scope}`); - expect(cacheNames.runtime).to.equal(`workbox-test-runtime-${self.registration.scope}`); + expect(cacheNames.precache).to.equal( + `workbox-precache-${self.registration.scope}`, + ); + expect(cacheNames.runtime).to.equal( + `workbox-test-runtime-${self.registration.scope}`, + ); }); - it('should allow customising the googleAnalytics name', function() { + it('should allow customising the googleAnalytics name', function () { setCacheNameDetails({googleAnalytics: 'test-ga'}); // Scope be default is '/' from 'service-worker-mock' - expect(cacheNames.googleAnalytics).to.equal(`workbox-test-ga-${self.registration.scope}`); + expect(cacheNames.googleAnalytics).to.equal( + `workbox-test-ga-${self.registration.scope}`, + ); }); - it('should allow customising all', function() { + it('should allow customising all', function () { setCacheNameDetails({ prefix: 'test-prefix', suffix: 'test-suffix', @@ -83,12 +97,16 @@ describe(`cacheNames`, function() { }); // Scope be default is '/' from 'service-worker-mock' - expect(cacheNames.precache).to.equal(`test-prefix-test-precache-test-suffix`); + expect(cacheNames.precache).to.equal( + `test-prefix-test-precache-test-suffix`, + ); expect(cacheNames.runtime).to.equal(`test-prefix-test-runtime-test-suffix`); - expect(cacheNames.googleAnalytics).to.equal(`test-prefix-test-ga-test-suffix`); + expect(cacheNames.googleAnalytics).to.equal( + `test-prefix-test-ga-test-suffix`, + ); }); - it('should allow setting prefix and suffix to empty string', function() { + it('should allow setting prefix and suffix to empty string', function () { setCacheNameDetails({ prefix: '', suffix: '', @@ -103,7 +121,7 @@ describe(`cacheNames`, function() { expect(cacheNames.googleAnalytics).to.equal(`test-ga`); }); - it('should not allow precache to be an empty string in dev', function() { + it('should not allow precache to be an empty string in dev', function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -113,8 +131,7 @@ describe(`cacheNames`, function() { }, 'invalid-cache-name'); }); - - it('should not allow runtime to be an empty string in dev', function() { + it('should not allow runtime to be an empty string in dev', function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -124,7 +141,7 @@ describe(`cacheNames`, function() { }, 'invalid-cache-name'); }); - it('should not allow googleAnalytics to be an empty string in dev', function() { + it('should not allow googleAnalytics to be an empty string in dev', function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -134,62 +151,75 @@ describe(`cacheNames`, function() { }, 'invalid-cache-name'); }); - const badValues = [ - undefined, - null, - {}, - [], - true, - false, - ]; - generateVariantTests(`should handle bad prefix values in dev`, badValues, function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); + const badValues = [undefined, null, {}, [], true, false]; + generateVariantTests( + `should handle bad prefix values in dev`, + badValues, + function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); + + return expectError(() => { + setCacheNameDetails({ + prefix: variant, + }); + }, 'incorrect-type'); + }, + ); + + generateVariantTests( + `should handle bad suffix values in dev`, + badValues, + function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); + + return expectError(() => { + setCacheNameDetails({ + suffix: variant, + }); + }, 'incorrect-type'); + }, + ); + + generateVariantTests( + `should handle bad precache values in dev`, + badValues, + function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); + + return expectError(() => { + setCacheNameDetails({ + precache: variant, + }); + }, 'incorrect-type'); + }, + ); + + generateVariantTests( + `should handle bad runtime values in dev`, + badValues, + function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); + + return expectError(() => { + setCacheNameDetails({ + runtime: variant, + }); + }, 'incorrect-type'); + }, + ); + + generateVariantTests( + `should not throw in prod`, + badValues, + function (variant) { + if (process.env.NODE_ENV !== 'production') return this.skip(); - return expectError(() => { setCacheNameDetails({ prefix: variant, - }); - }, 'incorrect-type'); - }); - - generateVariantTests(`should handle bad suffix values in dev`, badValues, function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); - - return expectError(() => { - setCacheNameDetails({ suffix: variant, - }); - }, 'incorrect-type'); - }); - - generateVariantTests(`should handle bad precache values in dev`, badValues, function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); - - return expectError(() => { - setCacheNameDetails({ precache: variant, - }); - }, 'incorrect-type'); - }); - - generateVariantTests(`should handle bad runtime values in dev`, badValues, function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); - - return expectError(() => { - setCacheNameDetails({ runtime: variant, }); - }, 'incorrect-type'); - }); - - generateVariantTests(`should not throw in prod`, badValues, function(variant) { - if (process.env.NODE_ENV !== 'production') return this.skip(); - - setCacheNameDetails({ - prefix: variant, - suffix: variant, - precache: variant, - runtime: variant, - }); - }); + }, + ); }); diff --git a/test/workbox-core/sw/test-clientsClaim.mjs b/test/workbox-core/sw/test-clientsClaim.mjs index 61dd63696..4810f9142 100644 --- a/test/workbox-core/sw/test-clientsClaim.mjs +++ b/test/workbox-core/sw/test-clientsClaim.mjs @@ -8,15 +8,14 @@ import {clientsClaim} from 'workbox-core/clientsClaim.mjs'; - -describe(`clientsClaim`, function() { +describe(`clientsClaim`, function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should add an activate event listener that calls clientsClaim`, function() { + it(`should add an activate event listener that calls clientsClaim`, function () { const clientsClaimSpy = sandbox.stub(self.clients, 'claim'); sandbox.stub(self, 'addEventListener').callsFake((eventName, cb) => { diff --git a/test/workbox-core/sw/test-copyResponse.mjs b/test/workbox-core/sw/test-copyResponse.mjs index 78e449cde..058445b61 100644 --- a/test/workbox-core/sw/test-copyResponse.mjs +++ b/test/workbox-core/sw/test-copyResponse.mjs @@ -8,14 +8,14 @@ import {copyResponse} from 'workbox-core/copyResponse.mjs'; -describe(`copyResponse`, function() { +describe(`copyResponse`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); @@ -28,24 +28,30 @@ describe(`copyResponse`, function() { // Default to a "real" same-origin URL, unless there's one passed in. if (url === undefined) { - url = (new URL('/app.js', self.location.origin)).href; + url = new URL('/app.js', self.location.origin).href; } sandbox.replaceGetter(response, 'url', () => url); return response; }; - it(`should throw the expected exception when passed a cross-origin response`, async function() { + it(`should throw the expected exception when passed a cross-origin response`, async function () { const crossOriginResponse = makeResponse('https://cross-origin.com/app.js'); - await expectError(() => copyResponse(crossOriginResponse), 'cross-origin-copy-response'); + await expectError( + () => copyResponse(crossOriginResponse), + 'cross-origin-copy-response', + ); }); - it(`should throw the expected exception when passed an opaque response`, async function() { + it(`should throw the expected exception when passed an opaque response`, async function () { const opaqueResponse = makeResponse(''); - await expectError(() => copyResponse(opaqueResponse), 'cross-origin-copy-response'); + await expectError( + () => copyResponse(opaqueResponse), + 'cross-origin-copy-response', + ); }); - it(`should allow modifying a response via the modifier return value`, async function() { + it(`should allow modifying a response via the modifier return value`, async function () { const oldResponse = makeResponse(); const newResponse1 = await copyResponse(oldResponse, (init) => { // Test modifying the existing headers. @@ -73,7 +79,9 @@ describe(`copyResponse`, function() { }); // The `Content-Type` header comes from the body. - expect(newResponse2.headers.get('Content-Type')).to.equal('text/javascript'); + expect(newResponse2.headers.get('Content-Type')).to.equal( + 'text/javascript', + ); expect(newResponse2.headers.get('X-One')).to.equal(null); expect(newResponse2.headers.get('X-Two')).to.equal('2'); expect(newResponse2.status).to.equal(200); @@ -88,7 +96,9 @@ describe(`copyResponse`, function() { }); // The `Content-Type` header comes from the body. - expect(newResponse3.headers.get('Content-Type')).to.equal('text/javascript'); + expect(newResponse3.headers.get('Content-Type')).to.equal( + 'text/javascript', + ); expect(newResponse3.headers.get('X-One')).to.equal(null); expect(newResponse3.headers.get('X-Two')).to.equal('2'); expect(newResponse3.headers.get('X-Three')).to.equal('3'); @@ -97,7 +107,7 @@ describe(`copyResponse`, function() { expect(await newResponse3.text()).to.equal('console.log()'); }); - it(`should copy a response as-is when no modifier is passed`, async function() { + it(`should copy a response as-is when no modifier is passed`, async function () { const oldResponse = makeResponse(); const newResponse = await copyResponse(oldResponse); diff --git a/test/workbox-core/sw/test-registerQuotaErrorCallback.mjs b/test/workbox-core/sw/test-registerQuotaErrorCallback.mjs index e9d22c977..d63acb14f 100644 --- a/test/workbox-core/sw/test-registerQuotaErrorCallback.mjs +++ b/test/workbox-core/sw/test-registerQuotaErrorCallback.mjs @@ -8,9 +8,8 @@ import {registerQuotaErrorCallback} from 'workbox-core/registerQuotaErrorCallback.mjs'; - -describe(`registerQuotaErrorCallback()`, function() { - it(`should throw when passed a non-function in dev mode`, async function() { +describe(`registerQuotaErrorCallback()`, function () { + it(`should throw when passed a non-function in dev mode`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); await expectError(() => registerQuotaErrorCallback(null), 'incorrect-type'); diff --git a/test/workbox-core/sw/test-skipWaiting.mjs b/test/workbox-core/sw/test-skipWaiting.mjs index b6a6eac95..9a516af38 100644 --- a/test/workbox-core/sw/test-skipWaiting.mjs +++ b/test/workbox-core/sw/test-skipWaiting.mjs @@ -9,14 +9,14 @@ import {logger} from 'workbox-core/_private/logger.mjs'; import {skipWaiting} from 'workbox-core/skipWaiting.mjs'; -describe(`skipWaiting`, function() { +describe(`skipWaiting`, function () { const sandbox = sinon.createSandbox(); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should call self.skipWaiting()`, function() { + it(`should call self.skipWaiting()`, function () { const skipWaitingStub = sandbox.stub(self, 'skipWaiting'); skipWaiting(); @@ -24,7 +24,7 @@ describe(`skipWaiting`, function() { expect(skipWaitingStub.callCount).to.eql(1); }); - it(`should log a warning message in development`, function() { + it(`should log a warning message in development`, function () { if (process.env.NODE_ENV === 'production') { this.skip(); } diff --git a/test/workbox-expiration/integration/test-all.js b/test/workbox-expiration/integration/test-all.js index 09d65ff2d..74064c501 100644 --- a/test/workbox-expiration/integration/test-all.js +++ b/test/workbox-expiration/integration/test-all.js @@ -13,32 +13,33 @@ const runInSW = require('../../../infra/testing/comlink/node-interface'); const waitUntil = require('../../../infra/testing/wait-until'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-expiration]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-expiration]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-expiration/sw/'); }); }); -describe(`[workbox-expiration] Plugin`, function() { +describe(`[workbox-expiration] Plugin`, function () { const baseURL = `${server.getAddress()}/test/workbox-expiration/static/expiration-plugin/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(webdriver, `${baseURL}integration.html`); }); - it(`should load a page with entries managed by maxEntries`, async function() { + it(`should load a page with entries managed by maxEntries`, async function () { const swURL = `${baseURL}sw-max-entries.js`; // Wait for the service worker to register and activate. await activateAndControlSW(swURL); let error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-1.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-1.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -52,17 +53,15 @@ describe(`[workbox-expiration] Plugin`, function() { }); const keys = await runInSW('cachesKeys'); - expect(keys).to.deep.equal([ - 'expiration-plugin-max-entries', - ]); + expect(keys).to.deep.equal(['expiration-plugin-max-entries']); let cachedRequests = await runInSW('cacheURLs', keys[0]); - expect(cachedRequests).to.eql([ - `${baseURL}example-1.txt`, - ]); + expect(cachedRequests).to.eql([`${baseURL}example-1.txt`]); error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-2.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-2.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -72,19 +71,23 @@ describe(`[workbox-expiration] Plugin`, function() { // to wait before the cache has be cleaned up. await waitUntil(async () => { cachedRequests = await runInSW('cacheURLs', keys[0]); - return (cachedRequests.length === 1 && - cachedRequests[0] === `${baseURL}example-2.txt`); + return ( + cachedRequests.length === 1 && + cachedRequests[0] === `${baseURL}example-2.txt` + ); }); }); - it(`should load a page with entries managed by maxAgeSeconds`, async function() { + it(`should load a page with entries managed by maxAgeSeconds`, async function () { const swURL = `${baseURL}sw-max-age-seconds.js`; // Wait for the service worker to register and activate. await activateAndControlSW(swURL); let error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-1.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-1.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -98,14 +101,10 @@ describe(`[workbox-expiration] Plugin`, function() { }); const keys = await runInSW('cachesKeys'); - expect(keys).to.deep.equal([ - 'expiration-plugin-max-age-seconds', - ]); + expect(keys).to.deep.equal(['expiration-plugin-max-age-seconds']); let cachedRequests = await runInSW('cacheURLs', keys[0]); - expect(cachedRequests).to.eql([ - `${baseURL}example-1.txt`, - ]); + expect(cachedRequests).to.eql([`${baseURL}example-1.txt`]); // Wait 2 seconds to expire entry. await new Promise((resolve) => { @@ -113,7 +112,9 @@ describe(`[workbox-expiration] Plugin`, function() { }); error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-2.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-2.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -123,19 +124,23 @@ describe(`[workbox-expiration] Plugin`, function() { // to wait before the cache has be cleaned up. await waitUntil(async () => { cachedRequests = await runInSW('cacheURLs', keys[0]); - return (cachedRequests.length === 1 && - cachedRequests[0] === `${baseURL}example-2.txt`); + return ( + cachedRequests.length === 1 && + cachedRequests[0] === `${baseURL}example-2.txt` + ); }); }); - it(`should clean up when deleteCacheAndMetadata() is called`, async function() { + it(`should clean up when deleteCacheAndMetadata() is called`, async function () { const swURL = `${baseURL}sw-deletion.js`; // Wait for the service worker to register and activate. await activateAndControlSW(swURL); let error = await webdriver.executeAsyncScript((cb) => { - fetch(`example-1.txt`).then(() => cb()).catch((err) => cb(err.message)); + fetch(`example-1.txt`) + .then(() => cb()) + .catch((err) => cb(err.message)); }); if (error) { throw new Error(error); @@ -149,17 +154,19 @@ describe(`[workbox-expiration] Plugin`, function() { }); let keys = await runInSW('cachesKeys'); - expect(keys).to.deep.equal([ - 'expiration-plugin-deletion', - ]); + expect(keys).to.deep.equal(['expiration-plugin-deletion']); const existence = await runInSW('doesDbExist', 'workbox-expiration'); expect(existence).to.be.true; error = await webdriver.executeAsyncScript((cb) => { - navigator.serviceWorker.addEventListener('message', (event) => { - cb(event.data); - }, {once: true}); + navigator.serviceWorker.addEventListener( + 'message', + (event) => { + cb(event.data); + }, + {once: true}, + ); navigator.serviceWorker.controller.postMessage('delete'); }); if (error) { @@ -171,8 +178,13 @@ describe(`[workbox-expiration] Plugin`, function() { keys = await runInSW('cachesKeys'); expect(keys).to.deep.equal([]); - const entries = (await runInSW('getObjectStoreEntries', - 'workbox-expiration', 'cache-entries')).filter((entry) => { + const entries = ( + await runInSW( + 'getObjectStoreEntries', + 'workbox-expiration', + 'cache-entries', + ) + ).filter((entry) => { return entry.cacheName === 'expiration-plugin-deletion'; }); diff --git a/test/workbox-expiration/static/expiration-plugin/sw-deletion.js b/test/workbox-expiration/static/expiration-plugin/sw-deletion.js index 6740945ef..18db308e1 100644 --- a/test/workbox-expiration/static/expiration-plugin/sw-deletion.js +++ b/test/workbox-expiration/static/expiration-plugin/sw-deletion.js @@ -20,13 +20,11 @@ const expirationPlugin = new workbox.expiration.ExpirationPlugin({ const cacheName = 'expiration-plugin-deletion'; workbox.routing.registerRoute( - /.*.txt/, - new workbox.strategies.CacheFirst({ - cacheName, - plugins: [ - expirationPlugin, - ], - }), + /.*.txt/, + new workbox.strategies.CacheFirst({ + cacheName, + plugins: [expirationPlugin], + }), ); self.addEventListener('message', async (event) => { diff --git a/test/workbox-expiration/static/expiration-plugin/sw-max-age-seconds.js b/test/workbox-expiration/static/expiration-plugin/sw-max-age-seconds.js index 08c9bab61..0525d38b8 100644 --- a/test/workbox-expiration/static/expiration-plugin/sw-max-age-seconds.js +++ b/test/workbox-expiration/static/expiration-plugin/sw-max-age-seconds.js @@ -13,16 +13,20 @@ importScripts('/__WORKBOX/buildFile/workbox-strategies'); importScripts('/infra/testing/comlink/sw-interface.js'); workbox.routing.registerRoute( - /.*.txt/, - new workbox.strategies.CacheFirst({ - cacheName: 'expiration-plugin-max-age-seconds', - plugins: [ - new workbox.expiration.ExpirationPlugin({ - maxAgeSeconds: 1, - }), - ], - }), + /.*.txt/, + new workbox.strategies.CacheFirst({ + cacheName: 'expiration-plugin-max-age-seconds', + plugins: [ + new workbox.expiration.ExpirationPlugin({ + maxAgeSeconds: 1, + }), + ], + }), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-expiration/static/expiration-plugin/sw-max-entries.js b/test/workbox-expiration/static/expiration-plugin/sw-max-entries.js index 84575e1ac..bbb94ad35 100644 --- a/test/workbox-expiration/static/expiration-plugin/sw-max-entries.js +++ b/test/workbox-expiration/static/expiration-plugin/sw-max-entries.js @@ -13,16 +13,20 @@ importScripts('/__WORKBOX/buildFile/workbox-strategies'); importScripts('/infra/testing/comlink/sw-interface.js'); workbox.routing.registerRoute( - /.*.txt/, - new workbox.strategies.CacheFirst({ - cacheName: 'expiration-plugin-max-entries', - plugins: [ - new workbox.expiration.ExpirationPlugin({ - maxEntries: 1, - }), - ], - }), + /.*.txt/, + new workbox.strategies.CacheFirst({ + cacheName: 'expiration-plugin-max-entries', + plugins: [ + new workbox.expiration.ExpirationPlugin({ + maxEntries: 1, + }), + ], + }), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-expiration/static/isURLExpired.html b/test/workbox-expiration/static/isURLExpired.html index f0e8639ee..d09edcba8 100644 --- a/test/workbox-expiration/static/isURLExpired.html +++ b/test/workbox-expiration/static/isURLExpired.html @@ -1,38 +1,40 @@ - - - -

    Log time of isURLExpired(); -

    + + + +

    Log time of isURLExpired();

    - + - - - + + - + setTimeout(test, 2000); + + diff --git a/test/workbox-expiration/sw/test-CacheExpiration.mjs b/test/workbox-expiration/sw/test-CacheExpiration.mjs index 8e0a81891..0ba7675c1 100644 --- a/test/workbox-expiration/sw/test-CacheExpiration.mjs +++ b/test/workbox-expiration/sw/test-CacheExpiration.mjs @@ -10,12 +10,11 @@ import {CacheTimestampsModel} from 'workbox-expiration/models/CacheTimestampsMod import {CacheExpiration} from 'workbox-expiration/CacheExpiration.mjs'; import {openDB} from 'idb'; - -describe(`CacheExpiration`, function() { +describe(`CacheExpiration`, function () { const sandbox = sinon.createSandbox(); let db = null; - beforeEach(async function() { + beforeEach(async function () { db = await openDB('workbox-expiration', 1, { upgrade: CacheTimestampsModel.prototype._upgradeDb, }); @@ -29,28 +28,35 @@ describe(`CacheExpiration`, function() { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`should be able to construct with cacheName and maxEntries`, function() { - const expirationManager = new CacheExpiration('test-cache', {maxEntries: 10}); + describe(`constructor`, function () { + it(`should be able to construct with cacheName and maxEntries`, function () { + const expirationManager = new CacheExpiration('test-cache', { + maxEntries: 10, + }); expect(expirationManager._maxEntries).to.equal(10); }); - it(`should be able to construct with cacheName and maxAgeSeconds`, function() { - const expirationManager = new CacheExpiration('test-cache', {maxAgeSeconds: 10}); + it(`should be able to construct with cacheName and maxAgeSeconds`, function () { + const expirationManager = new CacheExpiration('test-cache', { + maxAgeSeconds: 10, + }); expect(expirationManager._maxAgeSeconds).to.equal(10); }); - it(`should be able to construct with cacheName, maxEntries and maxAgeSeconds`, function() { - const expirationManager = new CacheExpiration('test-cache', {maxEntries: 1, maxAgeSeconds: 2}); + it(`should be able to construct with cacheName, maxEntries and maxAgeSeconds`, function () { + const expirationManager = new CacheExpiration('test-cache', { + maxEntries: 1, + maxAgeSeconds: 2, + }); expect(expirationManager._maxEntries).to.equal(1); expect(expirationManager._maxAgeSeconds).to.equal(2); }); - it(`should be able to construct with cacheName, maxEntries and matchOptions`, function() { + it(`should be able to construct with cacheName, maxEntries and matchOptions`, function () { const expirationManager = new CacheExpiration('test-cache', { maxEntries: 1, matchOptions: { @@ -62,7 +68,7 @@ describe(`CacheExpiration`, function() { expect(expirationManager._matchOptions).to.eql({ignoreVary: true}); }); - it(`should throw with no config`, function() { + it(`should throw with no config`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -73,8 +79,8 @@ describe(`CacheExpiration`, function() { // TODO Bad constructor input }); - describe(`expireEntries()`, function() { - it(`should expire and delete expired entries`, async function() { + describe(`expireEntries()`, function () { + it(`should expire and delete expired entries`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['Date'], }); @@ -87,13 +93,19 @@ describe(`CacheExpiration`, function() { const timestampModel = new CacheTimestampsModel(cacheName); await timestampModel.setTimestamp('/one', Date.now()); - await cache.put(`${location.origin}/one`, new Response('Injected request')); + await cache.put( + `${location.origin}/one`, + new Response('Injected request'), + ); clock.tick(5000); // Add another entry after 5 seconds. await timestampModel.setTimestamp('/two', Date.now()); - await cache.put(`${location.origin}/two`, new Response('Injected request')); + await cache.put( + `${location.origin}/two`, + new Response('Injected request'), + ); // Ensure both entries are still present after an initial expire. await expirationManager.expireEntries(); @@ -134,7 +146,7 @@ describe(`CacheExpiration`, function() { expect(cachedRequests).to.deep.equal([]); }); - it(`should expire and delete entries beyond maximum entries`, async function() { + it(`should expire and delete entries beyond maximum entries`, async function () { const cacheName = 'max-and-delete'; const maxEntries = 1; const currentTimestamp = Date.now(); @@ -142,7 +154,10 @@ describe(`CacheExpiration`, function() { const timestampModel = new CacheTimestampsModel(cacheName); await timestampModel.setTimestamp('/first', currentTimestamp); - await cache.put(`${location.origin}/first`, new Response('Injected request')); + await cache.put( + `${location.origin}/first`, + new Response('Injected request'), + ); const expirationManager = new CacheExpiration(cacheName, {maxEntries}); @@ -150,7 +165,10 @@ describe(`CacheExpiration`, function() { // Add entry and ensure it is removed await timestampModel.setTimestamp('/second', currentTimestamp - 1000); - await cache.put(`${location.origin}/second`, new Response('Injected request')); + await cache.put( + `${location.origin}/second`, + new Response('Injected request'), + ); await expirationManager.expireEntries(); @@ -163,10 +181,15 @@ describe(`CacheExpiration`, function() { // Check cache has /first let cachedRequests = await cache.keys(); - expect(cachedRequests.map((req) => req.url)).to.deep.equal([`${location.origin}/first`]); + expect(cachedRequests.map((req) => req.url)).to.deep.equal([ + `${location.origin}/first`, + ]); await timestampModel.setTimestamp('/third', currentTimestamp + 1000); - await cache.put(`${location.origin}/third`, new Response('Injected request')); + await cache.put( + `${location.origin}/third`, + new Response('Injected request'), + ); await expirationManager.expireEntries(); @@ -179,10 +202,12 @@ describe(`CacheExpiration`, function() { // Check cache has /third cachedRequests = await cache.keys(); - expect(cachedRequests.map((req) => req.url)).to.deep.equal([`${location.origin}/third`]); + expect(cachedRequests.map((req) => req.url)).to.deep.equal([ + `${location.origin}/third`, + ]); }); - it(`should pass matchOptions to the underlying cache.delete() call`, async function() { + it(`should pass matchOptions to the underlying cache.delete() call`, async function () { const cacheName = 'matchOptions-test'; const maxEntries = 1; const currentTimestamp = Date.now(); @@ -193,7 +218,10 @@ describe(`CacheExpiration`, function() { sandbox.stub(self.caches, 'open').resolves(cache); await timestampModel.setTimestamp('/first', currentTimestamp); - await cache.put(`${location.origin}/first`, new Response('Injected request')); + await cache.put( + `${location.origin}/first`, + new Response('Injected request'), + ); const expirationManager = new CacheExpiration(cacheName, { maxEntries, @@ -205,16 +233,18 @@ describe(`CacheExpiration`, function() { // Add entry and ensure it is removed await timestampModel.setTimestamp('/second', currentTimestamp - 1000); - await cache.put(`${location.origin}/second`, new Response('Injected request')); + await cache.put( + `${location.origin}/second`, + new Response('Injected request'), + ); await expirationManager.expireEntries(); - expect(cacheDeleteSpy.args).to.eql([[ - `${location.origin}/second`, - {ignoreVary: true}, - ]]); + expect(cacheDeleteSpy.args).to.eql([ + [`${location.origin}/second`, {ignoreVary: true}], + ]); }); - it(`should queue up expireEntries calls`, async function() { + it(`should queue up expireEntries calls`, async function () { const expirationManager = new CacheExpiration('test', {maxEntries: 10}); sandbox.spy(expirationManager, 'expireEntries'); @@ -225,15 +255,19 @@ describe(`CacheExpiration`, function() { expirationManager.expireEntries(); expect(expirationManager.expireEntries.callCount).to.equal(3); - expect(CacheTimestampsModel.prototype.expireEntries.callCount).to.equal(1); + expect(CacheTimestampsModel.prototype.expireEntries.callCount).to.equal( + 1, + ); await expireDone; expect(expirationManager.expireEntries.callCount).to.equal(4); - expect(CacheTimestampsModel.prototype.expireEntries.callCount).to.equal(2); + expect(CacheTimestampsModel.prototype.expireEntries.callCount).to.equal( + 2, + ); }); - it(`should expire multiple expired entries`, async function() { + it(`should expire multiple expired entries`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['Date'], }); @@ -268,8 +302,8 @@ describe(`CacheExpiration`, function() { }); }); - describe(`updateTimestamp()`, function() { - it(`should update the timestamp for a url`, async function() { + describe(`updateTimestamp()`, function () { + it(`should update the timestamp for a url`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['Date'], }); @@ -293,17 +327,19 @@ describe(`CacheExpiration`, function() { }); }); - describe(`isURLExpired()`, function() { - it(`should throw when called without maxAgeSeconds`, function() { + describe(`isURLExpired()`, function () { + it(`should throw when called without maxAgeSeconds`, function () { if (process.env.NODE_ENV === 'production') this.skip(); - const expirationManager = new CacheExpiration('test-cache', {maxEntries: 1}); + const expirationManager = new CacheExpiration('test-cache', { + maxEntries: 1, + }); return expectError(() => { return expirationManager.isURLExpired(); }, 'expired-test-without-max-age'); }); - it(`should return boolean`, async function() { + it(`should return boolean`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['Date'], }); diff --git a/test/workbox-expiration/sw/test-CacheTimestampsModel.mjs b/test/workbox-expiration/sw/test-CacheTimestampsModel.mjs index cc7f0af41..af39de1dd 100644 --- a/test/workbox-expiration/sw/test-CacheTimestampsModel.mjs +++ b/test/workbox-expiration/sw/test-CacheTimestampsModel.mjs @@ -9,12 +9,11 @@ import {CacheTimestampsModel} from 'workbox-expiration/models/CacheTimestampsModel.mjs'; import {openDB} from 'idb'; - -describe(`CacheTimestampsModel`, function() { +describe(`CacheTimestampsModel`, function () { const sandbox = sinon.createSandbox(); let db = null; - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); db = await openDB('workbox-expiration', 1, { upgrade: CacheTimestampsModel.prototype._upgradeDb, @@ -22,7 +21,7 @@ describe(`CacheTimestampsModel`, function() { await db.clear('cache-entries'); }); - after(function() { + after(function () { sandbox.restore(); }); @@ -91,16 +90,16 @@ describe(`CacheTimestampsModel`, function() { return db; }; - describe(`constructor`, function() { - it(`should constructor with a cacheName`, function() { + describe(`constructor`, function () { + it(`should constructor with a cacheName`, function () { new CacheTimestampsModel('test-cache'); }); // TODO Test bad input }); - describe(`expireEntries()`, function() { - it(`should remove and return entries with timestamps below minTimestamp`, async function() { + describe(`expireEntries()`, function () { + it(`should remove and return entries with timestamps below minTimestamp`, async function () { await populateDb(); const model1 = new CacheTimestampsModel('cache-one'); @@ -113,13 +112,11 @@ describe(`CacheTimestampsModel`, function() { const model2 = new CacheTimestampsModel('cache-two'); const removedEntries2 = await model2.expireEntries(9); - expect(removedEntries2).to.deep.equal([ - `${location.origin}/3`, - ]); + expect(removedEntries2).to.deep.equal([`${location.origin}/3`]); expect(await db.count('cache-entries')).to.equal(7); }); - it(`should remove and return the oldest entries greater than maxCount`, async function() { + it(`should remove and return the oldest entries greater than maxCount`, async function () { await populateDb(); const model1 = new CacheTimestampsModel('cache-one'); @@ -140,7 +137,7 @@ describe(`CacheTimestampsModel`, function() { expect(await db.count('cache-entries')).to.equal(5); }); - it(`should work with minTimestamp and maxCount`, async function() { + it(`should work with minTimestamp and maxCount`, async function () { await populateDb(); const model1 = new CacheTimestampsModel('cache-one'); @@ -158,13 +155,11 @@ describe(`CacheTimestampsModel`, function() { // This example tests maxCount being more restrictive. const removedEntries2 = await model2.expireEntries(5, 2); - expect(removedEntries2).to.deep.equal([ - `${location.origin}/3`, - ]); + expect(removedEntries2).to.deep.equal([`${location.origin}/3`]); expect(await db.count('cache-entries')).to.equal(6); }); - it(`should return an empty array if nothing matches`, async function() { + it(`should return an empty array if nothing matches`, async function () { await populateDb(); const model = new CacheTimestampsModel('cache-one'); @@ -176,8 +171,8 @@ describe(`CacheTimestampsModel`, function() { }); }); - describe(`setTimestamp`, async function() { - it(`should put entries in the database`, async function() { + describe(`setTimestamp`, async function () { + it(`should put entries in the database`, async function () { const model1 = new CacheTimestampsModel('cache-one'); const model2 = new CacheTimestampsModel('cache-two'); @@ -208,8 +203,8 @@ describe(`CacheTimestampsModel`, function() { }); }); - describe(`getTimestamp`, async function() { - it(`should get an entry from the database by 'url'`, async function() { + describe(`getTimestamp`, async function () { + it(`should get an entry from the database by 'url'`, async function () { await populateDb(); const model1 = new CacheTimestampsModel('cache-one'); diff --git a/test/workbox-expiration/sw/test-ExpirationPlugin.mjs b/test/workbox-expiration/sw/test-ExpirationPlugin.mjs index e2b55bb88..5c5691f32 100644 --- a/test/workbox-expiration/sw/test-ExpirationPlugin.mjs +++ b/test/workbox-expiration/sw/test-ExpirationPlugin.mjs @@ -11,20 +11,19 @@ import {CacheExpiration} from 'workbox-expiration/CacheExpiration.mjs'; import {cacheNames} from 'workbox-core/_private/cacheNames.mjs'; import {executeQuotaErrorCallbacks} from 'workbox-core/_private/executeQuotaErrorCallbacks.mjs'; - -describe(`ExpirationPlugin`, function() { +describe(`ExpirationPlugin`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`should throw for no config`, function() { + describe(`constructor`, function () { + it(`should throw for no config`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -32,7 +31,7 @@ describe(`ExpirationPlugin`, function() { }, 'max-entries-or-age-required'); }); - it(`should throw for non-number maxEntries`, function() { + it(`should throw for non-number maxEntries`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -42,7 +41,7 @@ describe(`ExpirationPlugin`, function() { }, 'incorrect-type'); }); - it(`should throw for non-number maxAgeSeconds`, function() { + it(`should throw for non-number maxAgeSeconds`, function () { if (process.env.NODE_ENV === 'production') this.skip(); return expectError(() => { @@ -52,21 +51,21 @@ describe(`ExpirationPlugin`, function() { }, 'incorrect-type'); }); - it(`should construct with just maxAgeSeconds`, function() { + it(`should construct with just maxAgeSeconds`, function () { const plugin = new ExpirationPlugin({ maxAgeSeconds: 10, }); expect(plugin._maxAgeSeconds).to.equal(10); }); - it(`should construct with just maxEntries`, function() { + it(`should construct with just maxEntries`, function () { const plugin = new ExpirationPlugin({ maxEntries: 10, }); expect(plugin._config.maxEntries).to.equal(10); }); - it(`should register a quota error callback when purgeOnQuotaError is true`, async function() { + it(`should register a quota error callback when purgeOnQuotaError is true`, async function () { const plugin = new ExpirationPlugin({ maxEntries: 10, purgeOnQuotaError: true, @@ -78,7 +77,7 @@ describe(`ExpirationPlugin`, function() { expect(plugin.deleteCacheAndMetadata.calledOnce).to.be.true; }); - it(`should not register a quota error callback when purgeOnQuotaError is false`, async function() { + it(`should not register a quota error callback when purgeOnQuotaError is false`, async function () { const plugin = new ExpirationPlugin({ maxEntries: 10, purgeOnQuotaError: false, @@ -90,7 +89,7 @@ describe(`ExpirationPlugin`, function() { expect(plugin.deleteCacheAndMetadata.called).to.be.false; }); - it(`should pass matchOptions through to the CacheExpiration instance`, async function() { + it(`should pass matchOptions through to the CacheExpiration instance`, async function () { const plugin = new ExpirationPlugin({ maxEntries: 10, matchOptions: { @@ -103,13 +102,13 @@ describe(`ExpirationPlugin`, function() { }); }); - describe(`cachedResponseWillBeUsed()`, function() { - it(`should expose a cachedResponseWillBeUsed() method`, function() { + describe(`cachedResponseWillBeUsed()`, function () { + it(`should expose a cachedResponseWillBeUsed() method`, function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); expect(plugin).to.respondTo('cachedResponseWillBeUsed'); }); - it(`should return cachedResponse when cachedResponseWillBeUsed() is called and Responses Data header it valid`, async function() { + it(`should return cachedResponse when cachedResponseWillBeUsed() is called and Responses Data header it valid`, async function () { // Just to ensure no timing flakiness in test. sandbox.useFakeTimers({ toFake: ['Date'], @@ -123,11 +122,17 @@ describe(`ExpirationPlugin`, function() { const expirationManager = plugin._getCacheExpiration('test-cache'); sandbox.spy(expirationManager, 'expireEntries'); - expect(await plugin.cachedResponseWillBeUsed({request: new Request('/'), cacheName: 'test-cache', cachedResponse})).to.eql(cachedResponse); + expect( + await plugin.cachedResponseWillBeUsed({ + request: new Request('/'), + cacheName: 'test-cache', + cachedResponse, + }), + ).to.eql(cachedResponse); expect(expirationManager.expireEntries.callCount).to.equal(1); }); - it(`should return null when cachedResponseWillBeUsed() is called and Responses Date header is too old`, async function() { + it(`should return null when cachedResponseWillBeUsed() is called and Responses Date header is too old`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['Date'], }); @@ -143,20 +148,31 @@ describe(`ExpirationPlugin`, function() { const expirationManager = plugin._getCacheExpiration('test-cache'); sandbox.spy(expirationManager, 'expireEntries'); - expect(await plugin.cachedResponseWillBeUsed({request: new Request('/'), cacheName: 'test-cache', cachedResponse})).to.eql(null); + expect( + await plugin.cachedResponseWillBeUsed({ + request: new Request('/'), + cacheName: 'test-cache', + cachedResponse, + }), + ).to.eql(null); expect(expirationManager.expireEntries.callCount).to.equal(1); }); - it(`should handle a null cachedResponse`, async function() { + it(`should handle a null cachedResponse`, async function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); const expirationManager = plugin._getCacheExpiration('test-cache'); sandbox.spy(expirationManager, 'expireEntries'); - expect(await plugin.cachedResponseWillBeUsed({cacheName: 'test-cache', cachedResponse: null})).to.eql(null); + expect( + await plugin.cachedResponseWillBeUsed({ + cacheName: 'test-cache', + cachedResponse: null, + }), + ).to.eql(null); }); - it(`should update the timestamp for the request URL`, async function() { + it(`should update the timestamp for the request URL`, async function () { const plugin = new ExpirationPlugin({maxEntries: 10}); const expirationManager = plugin._getCacheExpiration('test-cache'); @@ -169,43 +185,49 @@ describe(`ExpirationPlugin`, function() { }); expect(expirationManager.updateTimestamp.callCount).to.equal(1); - expect(expirationManager.updateTimestamp.args[0][0]).to.equal(`${location.origin}/one`); + expect(expirationManager.updateTimestamp.args[0][0]).to.equal( + `${location.origin}/one`, + ); }); }); - describe(`_isResponseDateFresh()`, function() { - it(`should return true when maxAgeSeconds is not set`, function() { + describe(`_isResponseDateFresh()`, function () { + it(`should return true when maxAgeSeconds is not set`, function () { const plugin = new ExpirationPlugin({maxEntries: 1}); const isFresh = plugin._isResponseDateFresh(new Response('Hi')); expect(isFresh).to.equal(true); }); - it(`should return true when there is no Date header`, function() { + it(`should return true when there is no Date header`, function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); - const isFresh = plugin._isResponseDateFresh(new Response('Hi', { - // TODO: Remove this when https://github.com/pinterest/service-workers/issues/72 - // is fixed. - headers: {}, - })); + const isFresh = plugin._isResponseDateFresh( + new Response('Hi', { + // TODO: Remove this when https://github.com/pinterest/service-workers/issues/72 + // is fixed. + headers: {}, + }), + ); expect(isFresh).to.equal(true); }); - it(`should return true when the Date header is invalid`, function() { + it(`should return true when the Date header is invalid`, function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); - const isFresh = plugin._isResponseDateFresh(new Response('Hi', { - headers: {date: 'invalid header'}, - })); + const isFresh = plugin._isResponseDateFresh( + new Response('Hi', { + headers: {date: 'invalid header'}, + }), + ); expect(isFresh).to.equal(true); }); }); - describe(`cacheDidUpdate()`, function() { - it(`should expose a cacheDidUpdate() method`, function() { + describe(`cacheDidUpdate()`, function () { + it(`should expose a cacheDidUpdate() method`, function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); expect(plugin).to.respondTo('cacheDidUpdate'); }); - it(`should update timestamps and expire entries`, async function() { + it(`should update timestamps and expire entries`, async function () { const cacheName = 'test-cache'; const url = new URL('/test', self.location).toString(); const request = new Request(url); @@ -217,17 +239,19 @@ describe(`ExpirationPlugin`, function() { await plugin.cacheDidUpdate({cacheName, request}); expect(CacheExpiration.prototype.updateTimestamp.callCount).to.equal(1); - expect(CacheExpiration.prototype.updateTimestamp.args[0][0]).to.equal(url); + expect(CacheExpiration.prototype.updateTimestamp.args[0][0]).to.equal( + url, + ); expect(CacheExpiration.prototype.expireEntries.callCount).to.equal(1); }); }); - describe(`_getCacheExpiration()`, function() { - it(`should reject when called with the default runtime cache name`, async function() { + describe(`_getCacheExpiration()`, function () { + it(`should reject when called with the default runtime cache name`, async function () { const plugin = new ExpirationPlugin({maxAgeSeconds: 1}); await expectError( - () => plugin._getCacheExpiration(cacheNames.getRuntimeName()), - 'expire-custom-caches-only', + () => plugin._getCacheExpiration(cacheNames.getRuntimeName()), + 'expire-custom-caches-only', ); }); }); diff --git a/test/workbox-google-analytics/integration/test-all.js b/test/workbox-google-analytics/integration/test-all.js index b7a847253..4a946d4fd 100644 --- a/test/workbox-google-analytics/integration/test-all.js +++ b/test/workbox-google-analytics/integration/test-all.js @@ -16,13 +16,13 @@ const waitUntil = require('../../../infra/testing/wait-until'); // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-google-analytics]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-google-analytics]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-google-analytics/sw/'); }); }); -describe(`[workbox-google-analytics] initialize`, function() { +describe(`[workbox-google-analytics] initialize`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-google-analytics/static/basic-example/`; const swURL = `${testingURL}sw.js`; @@ -39,34 +39,39 @@ describe(`[workbox-google-analytics] initialize`, function() { const messageSW = (data, done) => { const messageChannel = new MessageChannel(); messageChannel.port1.onmessage = (evt) => done(evt.data); - navigator.serviceWorker.controller.postMessage( - data, [messageChannel.port2]); + navigator.serviceWorker.controller.postMessage(data, [ + messageChannel.port2, + ]); }; - before(async function() { + before(async function () { // Load the page and wait for the first service worker to activate. await webdriver.get(testingURL); await activateAndControlSW(swURL); }); - beforeEach(async function() { + beforeEach(async function () { // Reset the spied requests array. await webdriver.executeAsyncScript(messageSW, { action: 'clear-spied-requests', }); }); - it(`should load a page with service worker`, async function() { + it(`should load a page with service worker`, async function () { const err = await webdriver.executeAsyncScript((done) => { - fetch('https://www.google-analytics.com/analytics.js', {mode: 'no-cors'}) - .then(() => done(), (err) => done(err.message)); + fetch('https://www.google-analytics.com/analytics.js', { + mode: 'no-cors', + }).then( + () => done(), + (err) => done(err.message), + ); }); expect(err).to.not.exist; }); - it(`replay failed Google Analytics hits`, async function() { + it(`replay failed Google Analytics hits`, async function () { // Skip this test in browsers that don't support background sync. // TODO(philipwalton): figure out a way to work around this. const browserSupportsSync = await webdriver.executeScript(() => { @@ -144,12 +149,16 @@ describe(`[workbox-google-analytics] initialize`, function() { }); // Wait until all expected requests have replayed. - await waitUntil(async () => { - requests = await webdriver.executeAsyncScript(messageSW, { - action: 'get-spied-requests', - }); - return requests.length === 2; - }, 25, 200); + await waitUntil( + async () => { + requests = await webdriver.executeAsyncScript(messageSW, { + action: 'get-spied-requests', + }); + return requests.length === 2; + }, + 25, + 200, + ); // Parse the request bodies to set the params as an object and convert the // qt param to a number. diff --git a/test/workbox-google-analytics/static/basic-example/index.html b/test/workbox-google-analytics/static/basic-example/index.html index 60069cf7b..ee0c556a2 100644 --- a/test/workbox-google-analytics/static/basic-example/index.html +++ b/test/workbox-google-analytics/static/basic-example/index.html @@ -2,9 +2,9 @@ Workbox Google Analytics - - - + + + @@ -14,15 +14,20 @@

    Note: you need to manually register sw.js

    - + - - + + - + const indexStringBtn = document.querySelector('.js-index-unrevisioned'); + indexStringBtn.addEventListener('click', () => { + precacheController.addToCacheList([ + '/index.html', + {url: '/example.html'}, + ]); + }); + + diff --git a/test/workbox-precaching/static/cleanup-outdated-caches/sw.js b/test/workbox-precaching/static/cleanup-outdated-caches/sw.js index d76313ca2..ce157d102 100644 --- a/test/workbox-precaching/static/cleanup-outdated-caches/sw.js +++ b/test/workbox-precaching/static/cleanup-outdated-caches/sw.js @@ -11,12 +11,18 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); -workbox.precaching.precache([{ - url: 'test.txt', - revision: '1', -}]); +workbox.precaching.precache([ + { + url: 'test.txt', + revision: '1', + }, +]); workbox.precaching.cleanupOutdatedCaches(); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-precaching/static/precache-and-update/index.html b/test/workbox-precaching/static/precache-and-update/index.html index ff646dade..203a2ec7d 100644 --- a/test/workbox-precaching/static/precache-and-update/index.html +++ b/test/workbox-precaching/static/precache-and-update/index.html @@ -1,11 +1,15 @@ Test page for precache-and-update - - + +

    Workbox Precaching - precache-and-update

    - + diff --git a/test/workbox-precaching/static/precache-and-update/sw-1.js b/test/workbox-precaching/static/precache-and-update/sw-1.js index 25c48b23e..e5de60503 100644 --- a/test/workbox-precaching/static/precache-and-update/sw-1.js +++ b/test/workbox-precaching/static/precache-and-update/sw-1.js @@ -21,7 +21,8 @@ workbox.precaching.precache([ { url: 'styles/index.css', revision: '1', - }, { + }, + { url: 'index.html', revision: '1', }, @@ -29,5 +30,9 @@ workbox.precaching.precache([ workbox.precaching.addRoute(); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-precaching/static/precache-and-update/sw-2.js b/test/workbox-precaching/static/precache-and-update/sw-2.js index a97e86323..edd276524 100644 --- a/test/workbox-precaching/static/precache-and-update/sw-2.js +++ b/test/workbox-precaching/static/precache-and-update/sw-2.js @@ -21,5 +21,9 @@ workbox.precaching.precache([ workbox.precaching.addRoute(); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-precaching/static/precache.html b/test/workbox-precaching/static/precache.html index 7a63847b3..4db30d088 100644 --- a/test/workbox-precaching/static/precache.html +++ b/test/workbox-precaching/static/precache.html @@ -1,52 +1,52 @@ - - - -

    precache.install() & precache.activate()

    - - + + + +

    precache.install() & precache.activate()

    + + - - - + + + - - + const activateBtn = document.querySelector('.js-index-activate'); + activateBtn.addEventListener('click', (event) => { + const precacheController = new workbox.precaching.PrecacheController(); + precacheController.addToCacheList(lastInstallValues); + precacheController.activate(event); + }); + + diff --git a/test/workbox-precaching/sw/resetDefaultPrecacheController.mjs b/test/workbox-precaching/sw/resetDefaultPrecacheController.mjs index 6e760ec84..7d8f77f3b 100644 --- a/test/workbox-precaching/sw/resetDefaultPrecacheController.mjs +++ b/test/workbox-precaching/sw/resetDefaultPrecacheController.mjs @@ -8,7 +8,6 @@ import {getOrCreatePrecacheController} from 'workbox-precaching/utils/getOrCreatePrecacheController.mjs'; - export function resetDefaultPrecacheController() { const pc = getOrCreatePrecacheController(); diff --git a/test/workbox-precaching/sw/test-PrecacheController.mjs b/test/workbox-precaching/sw/test-PrecacheController.mjs index 7d82315b7..bd52b19c7 100644 --- a/test/workbox-precaching/sw/test-PrecacheController.mjs +++ b/test/workbox-precaching/sw/test-PrecacheController.mjs @@ -13,7 +13,6 @@ import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.m import {spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import generateTestVariants from '../../../infra/testing/generate-variant-tests'; - function createFetchEvent(url) { const event = new FetchEvent('fetch', { request: new Request(url), @@ -22,10 +21,10 @@ function createFetchEvent(url) { return event; } -describe(`PrecacheController`, function() { +describe(`PrecacheController`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); @@ -47,33 +46,33 @@ describe(`PrecacheController`, function() { } }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - describe(`constructor`, function() { - it(`should construct without any inputs`, async function() { + describe(`constructor`, function () { + it(`should construct without any inputs`, async function () { expect(() => { new PrecacheController(); }).to.not.throw(); }); - it(`should construct with a valid cache name`, async function() { + it(`should construct with a valid cache name`, async function () { expect(() => { new PrecacheController({cacheName: 'test-cache-name'}); }).to.not.throw(); }); - it(`should pass the 'cacheName' option to the strategy`, async function() { + it(`should pass the 'cacheName' option to the strategy`, async function () { const cacheName = 'test-cache-name'; const pc = new PrecacheController({cacheName}); expect(pc.strategy.cacheName).to.equal(cacheName); }); - it(`should pass the 'plugins' option to the strategy`, async function() { + it(`should pass the 'plugins' option to the strategy`, async function () { const plugin = {}; const plugins = [plugin]; const pc = new PrecacheController({plugins}); @@ -82,7 +81,7 @@ describe(`PrecacheController`, function() { expect(pc.strategy.plugins).to.include(plugin); }); - it(`should pass the 'fallbackToNetwork' option to the strategy`, async function() { + it(`should pass the 'fallbackToNetwork' option to the strategy`, async function () { const pc = new PrecacheController({ cacheName: 'test', fallbackToNetwork: false, @@ -103,46 +102,41 @@ describe(`PrecacheController`, function() { }); }); - describe(`addToCacheList()`, function() { - const badTopLevelInputs = [ - {}, - true, - false, - 123, - '', - null, - undefined, - ]; - generateTestVariants(`should throw when passing in non-array values in dev`, badTopLevelInputs, async function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); + describe(`addToCacheList()`, function () { + const badTopLevelInputs = [{}, true, false, 123, '', null, undefined]; + generateTestVariants( + `should throw when passing in non-array values in dev`, + badTopLevelInputs, + async function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); - const precacheController = new PrecacheController(); - return expectError(() => { - precacheController.addToCacheList(variant); - }, 'not-an-array'); - }); + const precacheController = new PrecacheController(); + return expectError(() => { + precacheController.addToCacheList(variant); + }, 'not-an-array'); + }, + ); - const badNestedInputs = [ - true, - false, - 123, - null, - undefined, - [], - '', - {}, - ]; + const badNestedInputs = [true, false, 123, null, undefined, [], '', {}]; - generateTestVariants(`should throw when passing in invalid inputs in the array in dev`, badNestedInputs, async function(variant) { - if (process.env.NODE_ENV == 'production') return this.skip(); + generateTestVariants( + `should throw when passing in invalid inputs in the array in dev`, + badNestedInputs, + async function (variant) { + if (process.env.NODE_ENV == 'production') return this.skip(); - const precacheController = new PrecacheController(); - return expectError(() => { - precacheController.addToCacheList([variant]); - }, 'add-to-cache-list-unexpected-type', (err) => { - expect(err.details.entry).to.deep.equal(variant); - }); - }); + const precacheController = new PrecacheController(); + return expectError( + () => { + precacheController.addToCacheList([variant]); + }, + 'add-to-cache-list-unexpected-type', + (err) => { + expect(err.details.entry).to.deep.equal(variant); + }, + ); + }, + ); const unrevisionedEntryGroups = { 'string entries': [ @@ -162,14 +156,16 @@ describe(`PrecacheController`, function() { Object.keys(unrevisionedEntryGroups).forEach((groupName) => { const inputGroup = unrevisionedEntryGroups[groupName]; - it(`should add ${groupName} to cache list in dev`, async function() { + it(`should add ${groupName} to cache list in dev`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); const precacheController = new PrecacheController(); precacheController.addToCacheList(inputGroup); - expect(precacheController._urlsToCacheKeys.size).to.equal(inputGroup.length); + expect(precacheController._urlsToCacheKeys.size).to.equal( + inputGroup.length, + ); inputGroup.forEach((inputValue) => { const urlValue = new URL(inputValue.url || inputValue, location).href; @@ -179,13 +175,10 @@ describe(`PrecacheController`, function() { }); }); - it(`should remove duplicate ${groupName}`, async function() { + it(`should remove duplicate ${groupName}`, async function () { const precacheController = new PrecacheController(); - const inputURLs = [ - ...inputGroup, - ...inputGroup, - ]; + const inputURLs = [...inputGroup, ...inputGroup]; precacheController.addToCacheList(inputURLs); @@ -198,21 +191,18 @@ describe(`PrecacheController`, function() { }); }); - it(`should log a warning unless an entry has a revision property`, function() { - const logObject = process.env.NODE_ENV === 'production' ? console : logger; + it(`should log a warning unless an entry has a revision property`, function () { + const logObject = + process.env.NODE_ENV === 'production' ? console : logger; const warnStub = sandbox.stub(logObject, 'warn'); const precacheController = new PrecacheController(); - precacheController.addToCacheList([ - '/should-warn', - ]); + precacheController.addToCacheList(['/should-warn']); expect(warnStub.calledOnce).to.be.true; warnStub.resetHistory(); - precacheController.addToCacheList([ - {url: '/also-should-warn'}, - ]); + precacheController.addToCacheList([{url: '/also-should-warn'}]); expect(warnStub.calledOnce).to.be.true; warnStub.resetHistory(); @@ -223,7 +213,7 @@ describe(`PrecacheController`, function() { expect(warnStub.notCalled).to.be.true; }); - it(`should add url + revision objects to cache list`, async function() { + it(`should add url + revision objects to cache list`, async function () { const precacheController = new PrecacheController(); const inputObjects = [ @@ -242,42 +232,45 @@ describe(`PrecacheController`, function() { ]); }); - it(`should remove duplicate url + revision object entries`, async function() { + it(`should remove duplicate url + revision object entries`, async function () { const precacheController = new PrecacheController(); const singleObject = { url: new URL('/duplicate.html', location).href, revision: '123', }; - const inputObjects = [ - singleObject, - singleObject, - ]; + const inputObjects = [singleObject, singleObject]; precacheController.addToCacheList(inputObjects); expect(precacheController._urlsToCacheKeys.size).to.equal(1); - expect(precacheController._urlsToCacheKeys.has(singleObject.url)).to.be.true; + expect(precacheController._urlsToCacheKeys.has(singleObject.url)).to.be + .true; }); - it(`should throw on conflicting entries with different revisions`, async function() { + it(`should throw on conflicting entries with different revisions`, async function () { const firstEntry = {url: '/duplicate.html', revision: '123'}; const secondEntry = {url: '/duplicate.html', revision: '456'}; - return expectError(() => { - const precacheController = new PrecacheController(); - const inputObjects = [ - firstEntry, - secondEntry, - ]; - precacheController.addToCacheList(inputObjects); - }, 'add-to-cache-list-conflicting-entries', (err) => { - expect(err.details.firstEntry).to.eql(`${location.origin}/duplicate.html?__WB_REVISION__=123`); - expect(err.details.secondEntry).to.eql(`${location.origin}/duplicate.html?__WB_REVISION__=456`); - }); + return expectError( + () => { + const precacheController = new PrecacheController(); + const inputObjects = [firstEntry, secondEntry]; + precacheController.addToCacheList(inputObjects); + }, + 'add-to-cache-list-conflicting-entries', + (err) => { + expect(err.details.firstEntry).to.eql( + `${location.origin}/duplicate.html?__WB_REVISION__=123`, + ); + expect(err.details.secondEntry).to.eql( + `${location.origin}/duplicate.html?__WB_REVISION__=456`, + ); + }, + ); }); }); - describe(`install()`, function() { - it(`should be fine when calling with empty precache list`, async function() { + describe(`install()`, function () { + it(`should be fine when calling with empty precache list`, async function () { const event = new ExtendableEvent('install'); spyOnEvent(event); @@ -285,7 +278,7 @@ describe(`PrecacheController`, function() { return precacheController.install(event); }); - it(`should precache assets (with cache busting via search params)`, async function() { + it(`should precache assets (with cache busting via search params)`, async function () { const precacheController = new PrecacheController(); const cacheList = [ '/index.1234.html', @@ -328,13 +321,16 @@ describe(`PrecacheController`, function() { } }); - it(`should copy the response for redirected entries`, async function() { + it(`should copy the response for redirected entries`, async function () { self.fetch.restore(); sandbox.stub(self, 'fetch').callsFake((request) => { const response = new Response('Redirected Response'); sandbox.replaceGetter(response, 'redirected', () => true); - sandbox.replaceGetter(response, 'url', - () => (new URL(request.url, self.location.href)).href); + sandbox.replaceGetter( + response, + 'url', + () => new URL(request.url, self.location.href).href, + ); return response; }); @@ -351,7 +347,7 @@ describe(`PrecacheController`, function() { await precacheController.install(event); }); - it(`should use the desired cache name`, async function() { + it(`should use the desired cache name`, async function () { const precacheController = new PrecacheController({ cacheName: 'test-cache-name', }); @@ -382,7 +378,7 @@ describe(`PrecacheController`, function() { } }); - it(`should update assets that have changed`, async function() { + it(`should update assets that have changed`, async function () { const initialPrecacheController = new PrecacheController(); const initialCacheList = [ @@ -397,7 +393,9 @@ describe(`PrecacheController`, function() { const installEvent = new ExtendableEvent('install'); spyOnEvent(installEvent); - const initialInstallInfo = await initialPrecacheController.install(installEvent); + const initialInstallInfo = await initialPrecacheController.install( + installEvent, + ); const initialExpectedCacheKeys = [ `${location.origin}/index.1234.html`, @@ -417,12 +415,16 @@ describe(`PrecacheController`, function() { let cache = await caches.open(cacheNames.getPrecacheName()); const initialCacheKeys = await cache.keys(); // Get the url field out of each Request object. - expect(initialCacheKeys.map((r) => r.url)).to.have.members(initialExpectedCacheKeys); + expect(initialCacheKeys.map((r) => r.url)).to.have.members( + initialExpectedCacheKeys, + ); const activateEvent = new ExtendableEvent('activate'); spyOnEvent(activateEvent); - const initialActivateInfo = await initialPrecacheController.activate(activateEvent); + const initialActivateInfo = await initialPrecacheController.activate( + activateEvent, + ); expect(initialActivateInfo.deletedURLs).to.be.empty; // Make sure the files are cached after activation. @@ -442,7 +444,9 @@ describe(`PrecacheController`, function() { updatePrecacheController.addToCacheList(updateCacheList); - const updateInstallInfo = await updatePrecacheController.install(installEvent); + const updateInstallInfo = await updatePrecacheController.install( + installEvent, + ); expect(updateInstallInfo.updatedURLs).to.have.members([ `${location.origin}/index.4321.html`, @@ -472,7 +476,9 @@ describe(`PrecacheController`, function() { expect(logger.log.callCount).to.be.gt(0); } - const updateActivateInfo = await updatePrecacheController.activate(activateEvent); + const updateActivateInfo = await updatePrecacheController.activate( + activateEvent, + ); expect(updateActivateInfo.deletedURLs).to.have.members([ `${location.origin}/index.1234.html`, `${location.origin}/scripts/stress.js?test=search&foo=bar&__WB_REVISION__=1234`, @@ -489,7 +495,9 @@ describe(`PrecacheController`, function() { cache = await caches.open(cacheNames.getPrecacheName()); const postActivateUpdateCacheKeys = await cache.keys(); // Get the url field out of each Request object. - expect(postActivateUpdateCacheKeys.map((r) => r.url)).to.have.members(expectedPostActivateUpdateCacheKeys); + expect(postActivateUpdateCacheKeys.map((r) => r.url)).to.have.members( + expectedPostActivateUpdateCacheKeys, + ); // Make sure the files are cached after activation. for (const key of expectedPostActivateUpdateCacheKeys) { @@ -498,7 +506,7 @@ describe(`PrecacheController`, function() { } }); - it(`should precache with plugins`, async function() { + it(`should precache with plugins`, async function () { const plugins = [ { requestWillFetch: sandbox.stub().callsFake(({request}) => request), @@ -530,7 +538,7 @@ describe(`PrecacheController`, function() { expect(plugins[1].cacheWillUpdate.callCount).to.equal(4); }); - it(`should detect older precached versions in the cacheDidUpdate callback`, async function() { + it(`should detect older precached versions in the cacheDidUpdate callback`, async function () { // Restore fetch since this test depends on real fetch calls happening. self.fetch.restore(); @@ -548,9 +556,11 @@ describe(`PrecacheController`, function() { await precacheControllerV1.install(installEventV1); - const plugins = [{ - cacheDidUpdate: sandbox.stub().callsFake(({request}) => request), - }]; + const plugins = [ + { + cacheDidUpdate: sandbox.stub().callsFake(({request}) => request), + }, + ]; const precacheControllerV2 = new PrecacheController({plugins}); const cacheListV2 = [ @@ -572,10 +582,12 @@ describe(`PrecacheController`, function() { // match, but the bodies should be different. expect(c1.oldResponse.url).to.equal(c1.newResponse.url); expect(await c1.oldResponse.text()).to.not.equal( - await c1.newResponse.text()); + await c1.newResponse.text(), + ); expect(c2.oldResponse.url).to.equal(c2.newResponse.url); expect(await c2.oldResponse.text()).to.not.equal( - await c2.newResponse.text()); + await c2.newResponse.text(), + ); // For other resources it shouldn't find an old response. expect(c3.oldResponse).to.equal(undefined); @@ -584,7 +596,7 @@ describe(`PrecacheController`, function() { expect(c4.newResponse.url).to.equal(location.origin + cacheListV2[3].url); }); - it(`should use the proper 'this' when calling a cacheWillUpdate plugin`, async function() { + it(`should use the proper 'this' when calling a cacheWillUpdate plugin`, async function () { class TestPlugin { cacheWillUpdate({response}) { return response; @@ -597,9 +609,7 @@ describe(`PrecacheController`, function() { plugins: [pluginInstance], }); - const cacheList = [ - '/index.1234.html', - ]; + const cacheList = ['/index.1234.html']; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -610,11 +620,9 @@ describe(`PrecacheController`, function() { expect(cacheWillUpdateSpy.thisValues[0]).to.be.an.instanceof(TestPlugin); }); - it(`should set credentials: 'same-origin' on the precaching requests`, async function() { + it(`should set credentials: 'same-origin' on the precaching requests`, async function () { const precacheController = new PrecacheController(); - const cacheList = [ - '/index.1234.html', - ]; + const cacheList = ['/index.1234.html']; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -628,11 +636,9 @@ describe(`PrecacheController`, function() { expect(request.credentials).to.eql('same-origin'); }); - it(`should use cache: 'reload' on the precaching requests when there's a revision field`, async function() { + it(`should use cache: 'reload' on the precaching requests when there's a revision field`, async function () { const precacheController = new PrecacheController(); - const cacheList = [ - {url: '/test', revision: 'abcd'}, - ]; + const cacheList = [{url: '/test', revision: 'abcd'}]; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -647,11 +653,9 @@ describe(`PrecacheController`, function() { expect(request.cache).to.eql('reload'); }); - it(`should use cache: 'default' on the precaching requests when there's no revision field`, async function() { + it(`should use cache: 'default' on the precaching requests when there's no revision field`, async function () { const precacheController = new PrecacheController(); - const cacheList = [ - {url: '/test'}, - ]; + const cacheList = [{url: '/test'}]; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -666,13 +670,11 @@ describe(`PrecacheController`, function() { expect(request.cache).to.eql('default'); }); - it(`should pass in a request that includes the revision to cacheWrapper.put()`, async function() { + it(`should pass in a request that includes the revision to cacheWrapper.put()`, async function () { const putStub = sandbox.stub(Cache.prototype, 'put'); const precacheController = new PrecacheController(); - const cacheList = [ - {url: '/test', revision: 'abcd'}, - ]; + const cacheList = [{url: '/test', revision: 'abcd'}]; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -683,10 +685,12 @@ describe(`PrecacheController`, function() { expect(putStub.calledOnce).to.be.true; const request = putStub.args[0][0]; - expect(request.url).to.eql(`${location.origin}/test?__WB_REVISION__=abcd`); + expect(request.url).to.eql( + `${location.origin}/test?__WB_REVISION__=abcd`, + ); }); - it(`should use the integrity value when making requests`, async function() { + it(`should use the integrity value when making requests`, async function () { const precacheController = new PrecacheController(); const cacheList = [ {url: '/first'}, @@ -704,41 +708,45 @@ describe(`PrecacheController`, function() { expect(self.fetch.args[1][0].integrity).to.eql('sha256-second'); }); - it(`should fail when entries have the same url but different integrity`, function() { - return expectError(() => { - const precacheController = new PrecacheController(); - const cacheList = [ - {url: '/test', integrity: 'sha256-one'}, - {url: '/test', integrity: 'sha256-two'}, - ]; - precacheController.addToCacheList(cacheList); - }, 'add-to-cache-list-conflicting-integrities', (err) => { - expect(err.details.url).to.eql(`${location.origin}/test`); - }); + it(`should fail when entries have the same url but different integrity`, function () { + return expectError( + () => { + const precacheController = new PrecacheController(); + const cacheList = [ + {url: '/test', integrity: 'sha256-one'}, + {url: '/test', integrity: 'sha256-two'}, + ]; + precacheController.addToCacheList(cacheList); + }, + 'add-to-cache-list-conflicting-integrities', + (err) => { + expect(err.details.url).to.eql(`${location.origin}/test`); + }, + ); }); - it(`should fail installation when a response with a status of 400 is received`, async function() { + it(`should fail installation when a response with a status of 400 is received`, async function () { self.fetch.restore(); - sandbox.stub(self, 'fetch').resolves(new Response('', { - status: 400, - })); + sandbox.stub(self, 'fetch').resolves( + new Response('', { + status: 400, + }), + ); const precacheController = new PrecacheController(); - const cacheList = [ - '/will-be-error.html', - ]; + const cacheList = ['/will-be-error.html']; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); spyOnEvent(event); return expectError( - () => precacheController.install(event), - 'bad-precaching-response', + () => precacheController.install(event), + 'bad-precaching-response', ); }); - it(`should successfully install when an opaque response is received`, async function() { + it(`should successfully install when an opaque response is received`, async function () { self.fetch.restore(); sandbox.stub(self, 'fetch').callsFake(() => { const response = new Response('opaque'); @@ -747,9 +755,7 @@ describe(`PrecacheController`, function() { }); const precacheController = new PrecacheController(); - const cacheList = [ - '/will-be-opaque.html', - ]; + const cacheList = ['/will-be-opaque.html']; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -759,25 +765,27 @@ describe(`PrecacheController`, function() { await precacheController.install(event); }); - it(`should successfully install when a response with a status of 400 is received, if a cacheWillUpdate plugin allows it`, async function() { + it(`should successfully install when a response with a status of 400 is received, if a cacheWillUpdate plugin allows it`, async function () { self.fetch.restore(); - sandbox.stub(self, 'fetch').resolves(new Response('', { - status: 400, - })); - - const plugins = [{ - cacheWillUpdate: ({request, response}) => { - if (response.status === 400) { - return response; - } - return null; + sandbox.stub(self, 'fetch').resolves( + new Response('', { + status: 400, + }), + ); + + const plugins = [ + { + cacheWillUpdate: ({request, response}) => { + if (response.status === 400) { + return response; + } + return null; + }, }, - }]; + ]; const precacheController = new PrecacheController({plugins}); - const cacheList = [ - '/will-be-error.html', - ]; + const cacheList = ['/will-be-error.html']; precacheController.addToCacheList(cacheList); const event = new ExtendableEvent('install'); @@ -787,7 +795,7 @@ describe(`PrecacheController`, function() { await precacheController.install(event); }); - it(`should automatically call event.waitUntil()`, async function() { + it(`should automatically call event.waitUntil()`, async function () { const event = new ExtendableEvent('install'); spyOnEvent(event); @@ -797,24 +805,24 @@ describe(`PrecacheController`, function() { }); }); - describe(`activate()`, function() { - it(`should remove out of date entry`, async function() { + describe(`activate()`, function () { + it(`should remove out of date entry`, async function () { const cache = await caches.open(cacheNames.getPrecacheName()); const installEvent = new ExtendableEvent('install'); spyOnEvent(installEvent); // First precache some entries. const precacheControllerOne = new PrecacheController(); - const cacheList1 = [ - {url: '/scripts/index.js', revision: '1234'}, - ]; + const cacheList1 = [{url: '/scripts/index.js', revision: '1234'}]; precacheControllerOne.addToCacheList(cacheList1); await precacheControllerOne.install(installEvent); const activateEvent = new ExtendableEvent('activate'); spyOnEvent(activateEvent); - const cleanupDetailsOne = await precacheControllerOne.activate(activateEvent); + const cleanupDetailsOne = await precacheControllerOne.activate( + activateEvent, + ); expect(cleanupDetailsOne.deletedURLs.length).to.equal(0); const precacheControllerTwo = new PrecacheController(); @@ -822,15 +830,19 @@ describe(`PrecacheController`, function() { precacheControllerTwo.addToCacheList(cacheListTwo); await precacheControllerTwo.install(installEvent); - const cleanupDetailsTwo = await precacheControllerTwo.activate(activateEvent); + const cleanupDetailsTwo = await precacheControllerTwo.activate( + activateEvent, + ); expect(cleanupDetailsTwo.deletedURLs.length).to.equal(1); - expect(cleanupDetailsTwo.deletedURLs[0]).to.eql(`${location.origin}/scripts/index.js?__WB_REVISION__=1234`); + expect(cleanupDetailsTwo.deletedURLs[0]).to.eql( + `${location.origin}/scripts/index.js?__WB_REVISION__=1234`, + ); const keysTwo = await cache.keys(); expect(keysTwo.length).to.equal(cacheListTwo.length); }); - it(`should remove out of date entries`, async function() { + it(`should remove out of date entries`, async function () { const cache = await caches.open(cacheNames.getPrecacheName()); const installEvent = new ExtendableEvent('install'); spyOnEvent(installEvent); @@ -854,7 +866,9 @@ describe(`PrecacheController`, function() { const activateEvent = new ExtendableEvent('activate'); spyOnEvent(activateEvent); - const cleanupDetailsOne = await precacheControllerOne.activate(activateEvent); + const cleanupDetailsOne = await precacheControllerOne.activate( + activateEvent, + ); expect(cleanupDetailsOne.deletedURLs.length).to.equal(0); // Then, precache the same URLs, but two with different revisions. @@ -873,7 +887,9 @@ describe(`PrecacheController`, function() { logger.log.resetHistory(); } - const cleanupDetailsTwo = await precacheControllerTwo.activate(activateEvent); + const cleanupDetailsTwo = await precacheControllerTwo.activate( + activateEvent, + ); expect(cleanupDetailsTwo.deletedURLs).to.have.members([ `${location.origin}/index.1234.html`, `${location.origin}/scripts/stress.js?test=search&foo=bar&__WB_REVISION__=1234`, @@ -899,7 +915,7 @@ describe(`PrecacheController`, function() { } }); - it(`should automatically call event.waitUntil()`, async function() { + it(`should automatically call event.waitUntil()`, async function () { const event = new ExtendableEvent('activate'); spyOnEvent(event); @@ -909,8 +925,8 @@ describe(`PrecacheController`, function() { }); }); - describe(`getCachedURLs()`, function() { - it(`should return the cached URLs`, function() { + describe(`getCachedURLs()`, function () { + it(`should return the cached URLs`, function () { const precacheController = new PrecacheController(); const cacheList = [ '/index.1234.html', diff --git a/test/workbox-precaching/sw/test-PrecacheFallbackPlugin.mjs b/test/workbox-precaching/sw/test-PrecacheFallbackPlugin.mjs index 28fc8eab5..8899e1528 100644 --- a/test/workbox-precaching/sw/test-PrecacheFallbackPlugin.mjs +++ b/test/workbox-precaching/sw/test-PrecacheFallbackPlugin.mjs @@ -11,28 +11,30 @@ import {PrecacheController} from 'workbox-precaching/PrecacheController.mjs'; import {PrecacheFallbackPlugin} from 'workbox-precaching/PrecacheFallbackPlugin.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; -describe(`PrecacheFallbackPlugin`, function() { +describe(`PrecacheFallbackPlugin`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.stub(self, 'addEventListener'); resetDefaultPrecacheController(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`should construct a PrecacheFallbackPlugin instance with the default PrecacheController`, function() { + describe(`constructor`, function () { + it(`should construct a PrecacheFallbackPlugin instance with the default PrecacheController`, function () { const fallbackURL = '/test/url'; const precacheFallbackPlugin = new PrecacheFallbackPlugin({fallbackURL}); expect(precacheFallbackPlugin._fallbackURL).to.eql(fallbackURL); - expect(precacheFallbackPlugin._precacheController).to.be.instanceOf(PrecacheController); + expect(precacheFallbackPlugin._precacheController).to.be.instanceOf( + PrecacheController, + ); }); - it(`should construct a PrecacheFallbackPlugin instance with a non-default PrecacheController`, function() { + it(`should construct a PrecacheFallbackPlugin instance with a non-default PrecacheController`, function () { const fallbackURL = '/test/url'; const precacheController = new PrecacheController(); const precacheFallbackPlugin = new PrecacheFallbackPlugin({ @@ -41,10 +43,12 @@ describe(`PrecacheFallbackPlugin`, function() { }); expect(precacheFallbackPlugin._fallbackURL).to.eql(fallbackURL); - expect(precacheFallbackPlugin._precacheController).to.eql(precacheController); + expect(precacheFallbackPlugin._precacheController).to.eql( + precacheController, + ); }); - it(`should expose a handlerDidError method`, function() { + it(`should expose a handlerDidError method`, function () { const fallbackURL = '/test/url'; const precacheFallbackPlugin = new PrecacheFallbackPlugin({fallbackURL}); @@ -52,8 +56,8 @@ describe(`PrecacheFallbackPlugin`, function() { }); }); - describe(`handlerDidError`, function() { - it(`should return the matchPrecache value for the fallbackURL`, async function() { + describe(`handlerDidError`, function () { + it(`should return the matchPrecache value for the fallbackURL`, async function () { const body = 'test body'; const fallbackURL = '/test/url'; const revision = 'abcd1234'; @@ -63,10 +67,12 @@ describe(`PrecacheFallbackPlugin`, function() { match: matchStub, }); - precache([{ - revision, - url: fallbackURL, - }]); + precache([ + { + revision, + url: fallbackURL, + }, + ]); const precacheFallbackPlugin = new PrecacheFallbackPlugin({fallbackURL}); diff --git a/test/workbox-precaching/sw/test-PrecacheRoute.mjs b/test/workbox-precaching/sw/test-PrecacheRoute.mjs index 83c79f45f..44a54c082 100644 --- a/test/workbox-precaching/sw/test-PrecacheRoute.mjs +++ b/test/workbox-precaching/sw/test-PrecacheRoute.mjs @@ -9,7 +9,6 @@ import {PrecacheController} from 'workbox-precaching/PrecacheController.mjs'; import {PrecacheRoute} from 'workbox-precaching/PrecacheRoute.mjs'; - function createMatchParams(path) { const request = new Request(path); const url = new URL(request.url); @@ -17,9 +16,9 @@ function createMatchParams(path) { return {request, url, event}; } -describe(`PrecacheRoute()`, function() { - describe(`.match`, function() { - it(`should only match precached urls`, async function() { +describe(`PrecacheRoute()`, function () { + describe(`.match`, function () { + it(`should only match precached urls`, async function () { const pc = new PrecacheController(); pc.addToCacheList([ @@ -37,7 +36,7 @@ describe(`PrecacheRoute()`, function() { expect(pr.match(createMatchParams('/three'))).to.not.be.ok; }); - it(`matches precached urls with ignored params`, async function() { + it(`matches precached urls with ignored params`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/?a=1&b=2`]); @@ -46,13 +45,16 @@ describe(`PrecacheRoute()`, function() { }); const prWithoutIgnore = new PrecacheRoute(pc); - expect(prWithIgnore.match(createMatchParams('/?a=1&ignore=me&b=2'))).to.be.ok; - expect(prWithIgnore.match(createMatchParams('/?a=1&ignore=me&b=3'))).to.not.be.ok; - expect(prWithoutIgnore.match(createMatchParams('/?a=1&ignore=me&b=2'))).to.not.be.ok; + expect(prWithIgnore.match(createMatchParams('/?a=1&ignore=me&b=2'))).to.be + .ok; + expect(prWithIgnore.match(createMatchParams('/?a=1&ignore=me&b=3'))).to + .not.be.ok; + expect(prWithoutIgnore.match(createMatchParams('/?a=1&ignore=me&b=2'))).to + .not.be.ok; }); // Should we sort the search params to ensure that matches are consistent? - it.skip(`should match search params out of order`, async function() { + it.skip(`should match search params out of order`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/?a=1&b=2`]); @@ -61,11 +63,13 @@ describe(`PrecacheRoute()`, function() { }); const prWithoutIgnore = new PrecacheRoute(pc); - expect(prWithIgnore.match(createMatchParams('/?b=2&ignore=me&a=1'))).to.be.ok; - expect(prWithoutIgnore.match(createMatchParams('/?b=2&ignore=me&a=1'))).to.be.ok; + expect(prWithIgnore.match(createMatchParams('/?b=2&ignore=me&a=1'))).to.be + .ok; + expect(prWithoutIgnore.match(createMatchParams('/?b=2&ignore=me&a=1'))).to + .be.ok; }); - it(`should use the directoryIndex if the original request fails to match a cached URL`, async function() { + it(`should use the directoryIndex if the original request fails to match a cached URL`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/test-index.html`]); @@ -78,7 +82,7 @@ describe(`PrecacheRoute()`, function() { expect(prWithoutIndex.match(createMatchParams('/'))).to.not.be.ok; }); - it(`should use the default directoryIndex of 'index.html'`, async function() { + it(`should use the default directoryIndex of 'index.html'`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/index.html`]); @@ -87,7 +91,7 @@ describe(`PrecacheRoute()`, function() { expect(pr.match(createMatchParams('/'))).to.be.ok; }); - it(`should use the cleanURLs of 'about.html'`, async function() { + it(`should use the cleanURLs of 'about.html'`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/about.html`]); @@ -96,7 +100,7 @@ describe(`PrecacheRoute()`, function() { expect(pr.match(createMatchParams('/about'))).to.be.ok; }); - it(`should *not* use the cleanURLs of 'about.html' if set to false`, async function() { + it(`should *not* use the cleanURLs of 'about.html' if set to false`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/about.html`]); @@ -107,7 +111,7 @@ describe(`PrecacheRoute()`, function() { expect(pr.match(createMatchParams('/about'))).to.not.be.ok; }); - it(`should use a custom urlManipulation function`, async function() { + it(`should use a custom urlManipulation function`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/123.html`]); @@ -116,16 +120,14 @@ describe(`PrecacheRoute()`, function() { expect(url.pathname).to.equal('/'); const customURL = new URL(url); customURL.pathname = '123.html'; - return [ - customURL, - ]; + return [customURL]; }, }); expect(pr.match(createMatchParams('/'))).to.be.ok; }); - it(`should return null if there is no match`, async function() { + it(`should return null if there is no match`, async function () { const pc = new PrecacheController(); pc.addToCacheList([`/precached.html`]); @@ -135,8 +137,8 @@ describe(`PrecacheRoute()`, function() { }); }); - describe('.handler', function() { - it(`should use the PrecacheController's strategy as the handler`, function() { + describe('.handler', function () { + it(`should use the PrecacheController's strategy as the handler`, function () { const pc = new PrecacheController(); const pr = new PrecacheRoute(pc); @@ -144,8 +146,8 @@ describe(`PrecacheRoute()`, function() { }); }); - describe('.method', function() { - it(`defaults to GET`, function() { + describe('.method', function () { + it(`defaults to GET`, function () { const pc = new PrecacheController(); const pr = new PrecacheRoute(pc); diff --git a/test/workbox-precaching/sw/test-PrecacheStrategy.mjs b/test/workbox-precaching/sw/test-PrecacheStrategy.mjs index 8edf132a3..68e1ba122 100644 --- a/test/workbox-precaching/sw/test-PrecacheStrategy.mjs +++ b/test/workbox-precaching/sw/test-PrecacheStrategy.mjs @@ -8,8 +8,10 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.mjs'; import {PrecacheStrategy} from 'workbox-precaching/PrecacheStrategy.mjs'; -import {eventDoneWaiting, spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; - +import { + eventDoneWaiting, + spyOnEvent, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; function createFetchEvent(url, requestInit) { const event = new FetchEvent('fetch', { @@ -19,23 +21,23 @@ function createFetchEvent(url, requestInit) { return event; } -describe(`PrecacheStrategy()`, function() { +describe(`PrecacheStrategy()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`falls back to network by default on fetch`, async function() { + describe(`handle()`, function () { + it(`falls back to network by default on fetch`, async function () { sandbox.stub(self, 'fetch').callsFake((request) => { const response = new Response('Fetched Response'); sandbox.replaceGetter(response, 'url', () => request.url); @@ -60,7 +62,7 @@ describe(`PrecacheStrategy()`, function() { expect(cachedUrls).to.eql([`${location.origin}/one`]); }); - it(`falls back to network by default on fetch, and populates the cache if integrity is used`, async function() { + it(`falls back to network by default on fetch, and populates the cache if integrity is used`, async function () { sandbox.stub(self, 'fetch').callsFake((request) => { const response = new Response('Fetched Response'); sandbox.replaceGetter(response, 'url', () => request.url); @@ -121,7 +123,7 @@ describe(`PrecacheStrategy()`, function() { ]); }); - it(`just checks cache if fallbackToNetwork is false`, async function() { + it(`just checks cache if fallbackToNetwork is false`, async function () { sandbox.stub(self, 'fetch').callsFake((request) => { const response = new Response('Fetched Response'); sandbox.replaceGetter(response, 'url', () => request.url); @@ -138,10 +140,12 @@ describe(`PrecacheStrategy()`, function() { expect(self.fetch.callCount).to.equal(0); await expectError( - () => ps.handle(createFetchEvent('/two')), 'missing-precache-entry'); + () => ps.handle(createFetchEvent('/two')), + 'missing-precache-entry', + ); }); - it(`copies redirected responses`, async function() { + it(`copies redirected responses`, async function () { sandbox.stub(self, 'fetch').callsFake((request) => { const response = new Response('Redirected Response'); sandbox.replaceGetter(response, 'redirected', () => true); @@ -167,18 +171,22 @@ describe(`PrecacheStrategy()`, function() { expect(await cachedResponse.text()).to.equal('Redirected Response'); }); - it(`errors during install if the default plugin returns null`, async function() { + it(`errors during install if the default plugin returns null`, async function () { // Also ensure that we don't cache the bad response; // see https://github.com/GoogleChrome/workbox/issues/2737 const putStub = sandbox.stub().resolves(); sandbox.stub(self.caches, 'open').resolves({put: putStub}); - sandbox.stub(self, 'fetch').resolves(new Response('Server Error', { - status: 400, - })); + sandbox.stub(self, 'fetch').resolves( + new Response('Server Error', { + status: 400, + }), + ); const defaultPluginSpy = sandbox.spy( - PrecacheStrategy.defaultPrecacheCacheabilityPlugin, 'cacheWillUpdate'); + PrecacheStrategy.defaultPrecacheCacheabilityPlugin, + 'cacheWillUpdate', + ); const request = new Request('/index.html'); const event = new ExtendableEvent('install'); @@ -186,7 +194,9 @@ describe(`PrecacheStrategy()`, function() { const ps = new PrecacheStrategy(); await expectError( - () => ps.handle({event, request}), 'bad-precaching-response'); + () => ps.handle({event, request}), + 'bad-precaching-response', + ); await eventDoneWaiting(event); expect(putStub.callCount).to.eql(0); @@ -194,7 +204,7 @@ describe(`PrecacheStrategy()`, function() { expect(defaultPluginSpy.callCount).to.eql(1); }); - it(`doesn't error during install if the cacheWillUpdate plugin allows it`, async function() { + it(`doesn't error during install if the cacheWillUpdate plugin allows it`, async function () { const errorResponse = new Response('Server Error', { status: 400, }); @@ -207,16 +217,20 @@ describe(`PrecacheStrategy()`, function() { // Returning any valid Response will allow caching to proceed. const cacheWillUpdateStub = sandbox.stub().resolves(errorResponse); const defaultPluginSpy = sandbox.spy( - PrecacheStrategy.defaultPrecacheCacheabilityPlugin, 'cacheWillUpdate'); + PrecacheStrategy.defaultPrecacheCacheabilityPlugin, + 'cacheWillUpdate', + ); const request = new Request('/index.html'); const event = new ExtendableEvent('install'); spyOnEvent(event); const ps = new PrecacheStrategy({ - plugins: [{ - cacheWillUpdate: cacheWillUpdateStub, - }], + plugins: [ + { + cacheWillUpdate: cacheWillUpdateStub, + }, + ], }); const response = await ps.handle({event, request}); @@ -231,7 +245,7 @@ describe(`PrecacheStrategy()`, function() { expect(defaultPluginSpy.callCount).to.eql(0); }); - it(`errors during install if any of the cacheWillUpdate plugins return null`, async function() { + it(`errors during install if any of the cacheWillUpdate plugins return null`, async function () { const errorResponse = new Response('Server Error', { status: 400, }); @@ -245,22 +259,29 @@ describe(`PrecacheStrategy()`, function() { const cacheWillUpdateDenyStub = sandbox.stub().resolves(null); const defaultPluginSpy = sandbox.spy( - PrecacheStrategy.defaultPrecacheCacheabilityPlugin, 'cacheWillUpdate'); + PrecacheStrategy.defaultPrecacheCacheabilityPlugin, + 'cacheWillUpdate', + ); const request = new Request('/index.html'); const event = new ExtendableEvent('install'); spyOnEvent(event); const ps = new PrecacheStrategy({ - plugins: [{ - cacheWillUpdate: cacheWillUpdateAllowStub, - }, { - cacheWillUpdate: cacheWillUpdateDenyStub, - }], + plugins: [ + { + cacheWillUpdate: cacheWillUpdateAllowStub, + }, + { + cacheWillUpdate: cacheWillUpdateDenyStub, + }, + ], }); await expectError( - () => ps.handle({event, request}), 'bad-precaching-response'); + () => ps.handle({event, request}), + 'bad-precaching-response', + ); await eventDoneWaiting(event); @@ -271,8 +292,8 @@ describe(`PrecacheStrategy()`, function() { }); }); - describe('_useDefaultCacheabilityPluginIfNeeded()', function() { - it(`should include the expected plugins by default`, async function() { + describe('_useDefaultCacheabilityPluginIfNeeded()', function () { + it(`should include the expected plugins by default`, async function () { const ps = new PrecacheStrategy(); ps._useDefaultCacheabilityPluginIfNeeded(); @@ -292,7 +313,7 @@ describe(`PrecacheStrategy()`, function() { ]); }); - it(`should include the default plugin when the strategy has only non-cacheWillUpdate plugins`, async function() { + it(`should include the default plugin when the strategy has only non-cacheWillUpdate plugins`, async function () { const cacheKeyWillBeUsedPlugin = { cacheKeyWillBeUsed: sandbox.stub(), }; @@ -319,7 +340,7 @@ describe(`PrecacheStrategy()`, function() { ]); }); - it(`should not include the default plugin when the strategy has one cacheWillUpdate plugin`, async function() { + it(`should not include the default plugin when the strategy has one cacheWillUpdate plugin`, async function () { const cacheWillUpdatePlugin = { cacheWillUpdate: sandbox.stub(), }; @@ -344,7 +365,7 @@ describe(`PrecacheStrategy()`, function() { ]); }); - it(`should not include the default plugin when the strategy has multiple cacheWillUpdate plugins`, async function() { + it(`should not include the default plugin when the strategy has multiple cacheWillUpdate plugins`, async function () { const cacheWillUpdatePlugin1 = { cacheWillUpdate: sandbox.stub(), }; @@ -383,7 +404,7 @@ describe(`PrecacheStrategy()`, function() { ]); }); - it(`should remove the default plugin if a cacheWillUpdate plugin has been added after the initial call`, async function() { + it(`should remove the default plugin if a cacheWillUpdate plugin has been added after the initial call`, async function () { const cacheWillUpdatePlugin = { cacheWillUpdate: sandbox.stub(), }; @@ -409,35 +430,44 @@ describe(`PrecacheStrategy()`, function() { }); }); - describe('defaultPrecacheCacheabilityPlugin', function() { - it(`should return the same response when the status is 200`, async function() { + describe('defaultPrecacheCacheabilityPlugin', function () { + it(`should return the same response when the status is 200`, async function () { const response = new Response('', {status: 200}); - const returnedResponse = await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate({ - response, - }); + const returnedResponse = + await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate( + { + response, + }, + ); expect(returnedResponse).to.eql(response); }); - it(`should return the same response when the status is 0`, async function() { + it(`should return the same response when the status is 0`, async function () { // You can't construct opaque responses, so stub out the getter. const response = new Response('', {status: 599}); sandbox.stub(response, 'status').get(() => 0); - const returnedResponse = await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate({ - response, - }); + const returnedResponse = + await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate( + { + response, + }, + ); expect(returnedResponse).to.eql(response); }); - it(`should return null when the status is 404`, async function() { + it(`should return null when the status is 404`, async function () { const response = new Response('', {status: 404}); - const returnedResponse = await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate({ - response, - }); + const returnedResponse = + await PrecacheStrategy.defaultPrecacheCacheabilityPlugin.cacheWillUpdate( + { + response, + }, + ); expect(returnedResponse).to.be.null; }); diff --git a/test/workbox-precaching/sw/test-addPlugins.mjs b/test/workbox-precaching/sw/test-addPlugins.mjs index c9fbbc7c0..98faff883 100644 --- a/test/workbox-precaching/sw/test-addPlugins.mjs +++ b/test/workbox-precaching/sw/test-addPlugins.mjs @@ -10,9 +10,8 @@ import {addPlugins} from 'workbox-precaching/addPlugins.mjs'; import {precache} from 'workbox-precaching/precache.mjs'; import {getOrCreatePrecacheController} from 'workbox-precaching/utils/getOrCreatePrecacheController.mjs'; - -describe(`addPlugins()`, function() { - it(`should add plugins to the strategy`, async function() { +describe(`addPlugins()`, function () { + it(`should add plugins to the strategy`, async function () { const plugin1 = {}; const plugin2 = {}; diff --git a/test/workbox-precaching/sw/test-addRoute.mjs b/test/workbox-precaching/sw/test-addRoute.mjs index 6e49975b9..7d5e21e17 100644 --- a/test/workbox-precaching/sw/test-addRoute.mjs +++ b/test/workbox-precaching/sw/test-addRoute.mjs @@ -9,15 +9,14 @@ import {addRoute} from 'workbox-precaching/addRoute.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; - -describe(`addRoute()`, function() { +describe(`addRoute()`, function () { const sandbox = sinon.createSandbox(); function getAddedFetchListeners() { return self.addEventListener.args.filter(([type]) => type === 'fetch'); } - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); @@ -25,14 +24,14 @@ describe(`addRoute()`, function() { sandbox.spy(self, 'addEventListener'); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should add at most 1 fetch listener`, async function() { + it(`should add at most 1 fetch listener`, async function () { addRoute(); const callCountAfterFirstCall = getAddedFetchListeners().length; diff --git a/test/workbox-precaching/sw/test-cleanupOutdatedCaches.mjs b/test/workbox-precaching/sw/test-cleanupOutdatedCaches.mjs index b537efc17..e6b6fdd97 100644 --- a/test/workbox-precaching/sw/test-cleanupOutdatedCaches.mjs +++ b/test/workbox-precaching/sw/test-cleanupOutdatedCaches.mjs @@ -9,20 +9,19 @@ import {cleanupOutdatedCaches} from 'workbox-precaching/cleanupOutdatedCaches.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; - -describe(`cleanupOutdatedCaches()`, function() { +describe(`cleanupOutdatedCaches()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should add an activate listener`, async function() { + it(`should add an activate listener`, async function () { const addEventListenerSpy = sandbox.spy(self, 'addEventListener'); cleanupOutdatedCaches(); @@ -30,4 +29,3 @@ describe(`cleanupOutdatedCaches()`, function() { expect(addEventListenerSpy.firstCall.args[0]).to.eql('activate'); }); }); - diff --git a/test/workbox-precaching/sw/test-createHandlerBoundToURL.mjs b/test/workbox-precaching/sw/test-createHandlerBoundToURL.mjs index 60fc911ec..2ab76aea4 100644 --- a/test/workbox-precaching/sw/test-createHandlerBoundToURL.mjs +++ b/test/workbox-precaching/sw/test-createHandlerBoundToURL.mjs @@ -12,38 +12,48 @@ import {spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils. import {createHandlerBoundToURL} from 'workbox-precaching/createHandlerBoundToURL.mjs'; import {precache} from 'workbox-precaching/precache.mjs'; -describe(`createHandlerBoundToURL()`, function() { +describe(`createHandlerBoundToURL()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.stub(self, 'addEventListener'); resetDefaultPrecacheController(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should throw when passed a URL that isn't precached`, function() { + it(`should throw when passed a URL that isn't precached`, function () { precache([]); - return expectError(() => { - createHandlerBoundToURL('/does-not-exist'); - }, 'non-precached-url', (error) => expect(error.details.url).to.eql('/does-not-exist')); + return expectError( + () => { + createHandlerBoundToURL('/does-not-exist'); + }, + 'non-precached-url', + (error) => expect(error.details.url).to.eql('/does-not-exist'), + ); }); - it(`should return the expected handlerCallback for precached URLs`, async function() { + it(`should return the expected handlerCallback for precached URLs`, async function () { // Simulate the following: first two handlerCallbacks have cache.match() // calls that return a hit. Third, and subsequent handlerCallback has a // cache.match() call that's a miss, which will lead to a call to fetch(). - const matchStub = sandbox.stub(self.caches, 'match') - .onFirstCall().resolves(new Response('response 1')) - .onSecondCall().resolves(new Response('response 2')) - .resolves(undefined); - - const fetchStub = sandbox.stub(self, 'fetch') - .onFirstCall().resolves(new Response('response 3')) - .onSecondCall().resolves(new Response('response 4')); + const matchStub = sandbox + .stub(self.caches, 'match') + .onFirstCall() + .resolves(new Response('response 1')) + .onSecondCall() + .resolves(new Response('response 2')) + .resolves(undefined); + + const fetchStub = sandbox + .stub(self, 'fetch') + .onFirstCall() + .resolves(new Response('response 3')) + .onSecondCall() + .resolves(new Response('response 4')); precache([ '/url1', @@ -67,7 +77,9 @@ describe(`createHandlerBoundToURL()`, function() { const response2 = await handler2({event}); expect(matchStub.calledTwice).to.be.true; - expect(matchStub.secondCall.args[0].url).to.eql(`${location.origin}/url2?__WB_REVISION__=abc123`); + expect(matchStub.secondCall.args[0].url).to.eql( + `${location.origin}/url2?__WB_REVISION__=abc123`, + ); expect(fetchStub.notCalled).to.be.true; expect(await response2.text()).to.eql('response 2'); @@ -85,7 +97,9 @@ describe(`createHandlerBoundToURL()`, function() { expect(matchStub.callCount).to.eql(4); // Call #3 is the fourth call due to zero-indexing. - expect(matchStub.getCall(3).args[0].url).to.eql(`${location.origin}/url4?__WB_REVISION__=def456`); + expect(matchStub.getCall(3).args[0].url).to.eql( + `${location.origin}/url4?__WB_REVISION__=def456`, + ); expect(fetchStub.calledTwice).to.be.true; expect(fetchStub.secondCall.args[0].url).to.eql(`${location.origin}/url4`); expect(await response4.text()).to.eql('response 4'); diff --git a/test/workbox-precaching/sw/test-getCacheKeyForURL.mjs b/test/workbox-precaching/sw/test-getCacheKeyForURL.mjs index cb2252dff..57282831e 100644 --- a/test/workbox-precaching/sw/test-getCacheKeyForURL.mjs +++ b/test/workbox-precaching/sw/test-getCacheKeyForURL.mjs @@ -10,11 +10,10 @@ import {getCacheKeyForURL} from 'workbox-precaching/getCacheKeyForURL.mjs'; import {precache} from 'workbox-precaching/precache.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; - -describe(`getCacheKeyForURL()`, function() { +describe(`getCacheKeyForURL()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); @@ -22,19 +21,20 @@ describe(`getCacheKeyForURL()`, function() { sandbox.spy(self, 'addEventListener'); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should return the expected cache keys for various URLs`, async function() { + it(`should return the expected cache keys for various URLs`, async function () { precache(['/one', {url: '/two', revision: '1234'}]); expect(getCacheKeyForURL('/one')).to.eql(`${location.origin}/one`); - expect(getCacheKeyForURL(`${location.origin}/two`)) - .to.eql(`${location.origin}/two?__WB_REVISION__=1234`); + expect(getCacheKeyForURL(`${location.origin}/two`)).to.eql( + `${location.origin}/two?__WB_REVISION__=1234`, + ); expect(getCacheKeyForURL('/not-precached')).to.not.exist; }); }); diff --git a/test/workbox-precaching/sw/test-matchPrecache.mjs b/test/workbox-precaching/sw/test-matchPrecache.mjs index a41c28902..90785fa6e 100644 --- a/test/workbox-precaching/sw/test-matchPrecache.mjs +++ b/test/workbox-precaching/sw/test-matchPrecache.mjs @@ -10,35 +10,34 @@ import {matchPrecache} from 'workbox-precaching/matchPrecache.mjs'; import {precache} from 'workbox-precaching/precache.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; - -describe(`matchPrecache()`, function() { +describe(`matchPrecache()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.stub(self, 'addEventListener'); resetDefaultPrecacheController(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); // This is all into one big test with multiple expects() as that plays nicer // with precache()'s behavior. - it(`should behave as expected`, async function() { - const matchStub = sandbox.stub() - .onFirstCall().resolves(new Response('response 1')) - .onSecondCall().resolves(new Response('response 2')) - .resolves(undefined); + it(`should behave as expected`, async function () { + const matchStub = sandbox + .stub() + .onFirstCall() + .resolves(new Response('response 1')) + .onSecondCall() + .resolves(new Response('response 2')) + .resolves(undefined); sandbox.stub(self.caches, 'open').resolves({ match: matchStub, }); - precache([ - '/url1', - {url: '/url2', revision: 'abc123'}, - ]); + precache(['/url1', {url: '/url2', revision: 'abc123'}]); const noMatchResponse = await matchPrecache('does-not-match'); expect(noMatchResponse).to.be.undefined; @@ -53,7 +52,9 @@ describe(`matchPrecache()`, function() { const response2 = await matchPrecache(new Request('/url2')); expect(matchStub.calledTwice).to.be.true; - expect(matchStub.secondCall.args).to.eql([`${location.origin}/url2?__WB_REVISION__=abc123`]); + expect(matchStub.secondCall.args).to.eql([ + `${location.origin}/url2?__WB_REVISION__=abc123`, + ]); expect(await response2.text()).to.eql('response 2'); }); }); diff --git a/test/workbox-precaching/sw/test-precache.mjs b/test/workbox-precaching/sw/test-precache.mjs index 03a3ea10a..eff852191 100644 --- a/test/workbox-precaching/sw/test-precache.mjs +++ b/test/workbox-precaching/sw/test-precache.mjs @@ -12,11 +12,10 @@ import {getOrCreatePrecacheController} from 'workbox-precaching/utils/getOrCreat import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; import {dispatchAndWaitUntilDone} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; - -describe(`precache()`, function() { +describe(`precache()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); @@ -26,14 +25,14 @@ describe(`precache()`, function() { // The `addFetchListener` method adds a listener only the first time it's invoked, // so we can't remove that listener until all tests are run. - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should call install and activate on install and activate`, async function() { + it(`should call install and activate on install and activate`, async function () { const pc = getOrCreatePrecacheController(); sandbox.spy(pc, 'install'); @@ -52,17 +51,18 @@ describe(`precache()`, function() { expect(pc.activate.callCount).to.equal(1); }); - it(`should add entries to the default PrecacheController cache list`, async function() { + it(`should add entries to the default PrecacheController cache list`, async function () { sandbox.spy(PrecacheController.prototype, 'addToCacheList'); precache(['/one', '/two', '/three']); expect(PrecacheController.prototype.addToCacheList.callCount).to.equal(1); - expect(PrecacheController.prototype.addToCacheList.args[0][0]) - .to.deep.equal(['/one', '/two', '/three']); + expect( + PrecacheController.prototype.addToCacheList.args[0][0], + ).to.deep.equal(['/one', '/two', '/three']); }); - it(`shouldn't throw when precaching assets`, function() { + it(`shouldn't throw when precaching assets`, function () { precache([ 'index.1234.html', { diff --git a/test/workbox-precaching/sw/test-precacheAndRoute.mjs b/test/workbox-precaching/sw/test-precacheAndRoute.mjs index 827178fc0..33b386103 100644 --- a/test/workbox-precaching/sw/test-precacheAndRoute.mjs +++ b/test/workbox-precaching/sw/test-precacheAndRoute.mjs @@ -12,11 +12,10 @@ import {PrecacheRoute} from 'workbox-precaching/PrecacheRoute.mjs'; import {Router} from 'workbox-routing/Router.mjs'; import {resetDefaultPrecacheController} from './resetDefaultPrecacheController.mjs'; - -describe(`precacheAndRoute()`, function() { +describe(`precacheAndRoute()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); resetDefaultPrecacheController(); @@ -26,14 +25,14 @@ describe(`precacheAndRoute()`, function() { // The `addFetchListener` method adds a listener only the first time it's invoked, // so we can't remove that listener until all tests are run. - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should call precache() and addRoute() without args`, function() { + it(`should call precache() and addRoute() without args`, function () { const precache = sandbox.stub(PrecacheController.prototype, 'precache'); const registerRoute = sandbox.stub(Router.prototype, 'registerRoute'); @@ -44,7 +43,7 @@ describe(`precacheAndRoute()`, function() { expect(registerRoute.args[0][0]).to.be.instanceOf(PrecacheRoute); }); - it(`should call precache() and addRoute() with args`, function() { + it(`should call precache() and addRoute() with args`, function () { const precache = sandbox.stub(PrecacheController.prototype, 'precache'); const registerRoute = sandbox.stub(Router.prototype, 'registerRoute'); diff --git a/test/workbox-precaching/sw/utils/test-deleteOutdatedCaches.mjs b/test/workbox-precaching/sw/utils/test-deleteOutdatedCaches.mjs index f9600bf28..d23526a53 100644 --- a/test/workbox-precaching/sw/utils/test-deleteOutdatedCaches.mjs +++ b/test/workbox-precaching/sw/utils/test-deleteOutdatedCaches.mjs @@ -8,21 +8,20 @@ import {deleteOutdatedCaches} from 'workbox-precaching/utils/deleteOutdatedCaches.mjs'; - -describe(`deleteOutdatedCaches()`, function() { +describe(`deleteOutdatedCaches()`, function () { const CACHE_NAME = 'expected-precache-name'; const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - after(function() { + after(function () { sandbox.restore(); }); - it(`should not do anything when there are no caches`, async function() { + it(`should not do anything when there are no caches`, async function () { sandbox.stub(caches, 'keys').resolves([]); const cachesDeleteStub = sandbox.stub(caches, 'delete').resolves(); @@ -32,7 +31,7 @@ describe(`deleteOutdatedCaches()`, function() { expect(cachesDeleteStub.notCalled).to.be.true; }); - it(`should not do anything when there is only the expected cache`, async function() { + it(`should not do anything when there is only the expected cache`, async function () { sandbox.stub(caches, 'keys').resolves([CACHE_NAME]); const cachesDeleteStub = sandbox.stub(caches, 'delete').resolves(); @@ -42,12 +41,14 @@ describe(`deleteOutdatedCaches()`, function() { expect(cachesDeleteStub.notCalled).to.be.true; }); - it(`should delete everything that matches the deletion criteria`, async function() { - sandbox.stub(caches, 'keys').resolves([ - CACHE_NAME, - `this-precache-should-be-deleted1-${self.registration.scope}`, - `this-precache-should-be-deleted2-${self.registration.scope}`, - ]); + it(`should delete everything that matches the deletion criteria`, async function () { + sandbox + .stub(caches, 'keys') + .resolves([ + CACHE_NAME, + `this-precache-should-be-deleted1-${self.registration.scope}`, + `this-precache-should-be-deleted2-${self.registration.scope}`, + ]); const cachesDeleteStub = sandbox.stub(caches, 'delete').resolves(); const cachesDeleted = await deleteOutdatedCaches(CACHE_NAME); @@ -57,16 +58,22 @@ describe(`deleteOutdatedCaches()`, function() { `this-precache-should-be-deleted2-${self.registration.scope}`, ]); expect(cachesDeleteStub.calledTwice).to.be.true; - expect(cachesDeleteStub.firstCall.args).to.eql([`this-precache-should-be-deleted1-${self.registration.scope}`]); - expect(cachesDeleteStub.secondCall.args).to.eql([`this-precache-should-be-deleted2-${self.registration.scope}`]); + expect(cachesDeleteStub.firstCall.args).to.eql([ + `this-precache-should-be-deleted1-${self.registration.scope}`, + ]); + expect(cachesDeleteStub.secondCall.args).to.eql([ + `this-precache-should-be-deleted2-${self.registration.scope}`, + ]); }); - it(`should take SW scope into consideration as part of the criteria`, async function() { - sandbox.stub(caches, 'keys').resolves([ - CACHE_NAME, - `this-precache-should-not-be-deleted-no-scope-match`, - `this-precache-should-be-deleted-${self.registration.scope}`, - ]); + it(`should take SW scope into consideration as part of the criteria`, async function () { + sandbox + .stub(caches, 'keys') + .resolves([ + CACHE_NAME, + `this-precache-should-not-be-deleted-no-scope-match`, + `this-precache-should-be-deleted-${self.registration.scope}`, + ]); const cachesDeleteStub = sandbox.stub(caches, 'delete').resolves(); const cachesDeleted = await deleteOutdatedCaches(CACHE_NAME); @@ -75,16 +82,20 @@ describe(`deleteOutdatedCaches()`, function() { `this-precache-should-be-deleted-${self.registration.scope}`, ]); expect(cachesDeleteStub.calledOnce).to.be.true; - expect(cachesDeleteStub.firstCall.args).to.eql([`this-precache-should-be-deleted-${self.registration.scope}`]); + expect(cachesDeleteStub.firstCall.args).to.eql([ + `this-precache-should-be-deleted-${self.registration.scope}`, + ]); }); - it(`should support overriding the default '-precache-' substring criteria`, async function() { - sandbox.stub(caches, 'keys').resolves([ - CACHE_NAME, - `this-precache-should-not-be-deleted-${self.registration.scope}`, - `this-PRECACHE-should-be-deleted1-${self.registration.scope}`, - `this-PRECACHE-should-be-deleted2-${self.registration.scope}`, - ]); + it(`should support overriding the default '-precache-' substring criteria`, async function () { + sandbox + .stub(caches, 'keys') + .resolves([ + CACHE_NAME, + `this-precache-should-not-be-deleted-${self.registration.scope}`, + `this-PRECACHE-should-be-deleted1-${self.registration.scope}`, + `this-PRECACHE-should-be-deleted2-${self.registration.scope}`, + ]); const cachesDeleteStub = sandbox.stub(caches, 'delete').resolves(); const cachesDeleted = await deleteOutdatedCaches(CACHE_NAME, '-PRECACHE-'); @@ -94,7 +105,11 @@ describe(`deleteOutdatedCaches()`, function() { `this-PRECACHE-should-be-deleted2-${self.registration.scope}`, ]); expect(cachesDeleteStub.calledTwice).to.be.true; - expect(cachesDeleteStub.firstCall.args).to.eql([`this-PRECACHE-should-be-deleted1-${self.registration.scope}`]); - expect(cachesDeleteStub.secondCall.args).to.eql([`this-PRECACHE-should-be-deleted2-${self.registration.scope}`]); + expect(cachesDeleteStub.firstCall.args).to.eql([ + `this-PRECACHE-should-be-deleted1-${self.registration.scope}`, + ]); + expect(cachesDeleteStub.secondCall.args).to.eql([ + `this-PRECACHE-should-be-deleted2-${self.registration.scope}`, + ]); }); }); diff --git a/test/workbox-precaching/sw/utils/test-printCleanupDetails.mjs b/test/workbox-precaching/sw/utils/test-printCleanupDetails.mjs index bce0252ff..29ab4abc7 100644 --- a/test/workbox-precaching/sw/utils/test-printCleanupDetails.mjs +++ b/test/workbox-precaching/sw/utils/test-printCleanupDetails.mjs @@ -9,21 +9,20 @@ import {logger} from 'workbox-core/_private/logger.mjs'; import {printCleanupDetails} from 'workbox-precaching/utils/printCleanupDetails.mjs'; - -describe(`printCleanupDetails()`, function() { +describe(`printCleanupDetails()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { if (logger) { sandbox.spy(logger, 'log'); } }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`shouldn't print if nothing was deleted`, function() { + it(`shouldn't print if nothing was deleted`, function () { if (process.env.NODE_ENV === 'production') this.skip(); printCleanupDetails([], []); @@ -31,7 +30,7 @@ describe(`printCleanupDetails()`, function() { expect(logger.log.callCount).to.equal(0); }); - it(`should print at least one entry was delete`, function() { + it(`should print at least one entry was delete`, function () { if (process.env.NODE_ENV === 'production') this.skip(); printCleanupDetails(['/'], ['/']); @@ -39,7 +38,7 @@ describe(`printCleanupDetails()`, function() { expect(logger.log.callCount).to.be.gt(0); }); - it(`should print strings with multiple entries`, function() { + it(`should print strings with multiple entries`, function () { if (process.env.NODE_ENV === 'production') this.skip(); printCleanupDetails(['/', '/2'], ['/', '/2']); diff --git a/test/workbox-precaching/sw/utils/test-printInstallDetails.mjs b/test/workbox-precaching/sw/utils/test-printInstallDetails.mjs index 5ee6eae76..4166773c4 100644 --- a/test/workbox-precaching/sw/utils/test-printInstallDetails.mjs +++ b/test/workbox-precaching/sw/utils/test-printInstallDetails.mjs @@ -9,21 +9,20 @@ import {logger} from 'workbox-core/_private/logger.mjs'; import {printInstallDetails} from 'workbox-precaching/utils/printInstallDetails.mjs'; - -describe(`printInstallDetails()`, function() { +describe(`printInstallDetails()`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { if (logger) { sandbox.spy(logger, 'log'); } }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); - it(`should print with single update`, function() { + it(`should print with single update`, function () { if (process.env.NODE_ENV === 'production') this.skip(); printInstallDetails([], ['/index.html']); diff --git a/test/workbox-range-requests/integration/test-all.js b/test/workbox-range-requests/integration/test-all.js index c1ea8788e..35f060d30 100644 --- a/test/workbox-range-requests/integration/test-all.js +++ b/test/workbox-range-requests/integration/test-all.js @@ -11,48 +11,54 @@ const activateAndControlSW = require('../../../infra/testing/activate-and-contro const cleanSWEnv = require('../../../infra/testing/clean-sw'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-range-requests]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-range-requests]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-range-requests/sw/'); }); }); -describe(`[workbox-range-requests] Plugin`, function() { +describe(`[workbox-range-requests] Plugin`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-range-requests/static/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(webdriver, testingURL); }); - it(`should return a partial response that satisfies the request's Range: header, and an error response when it can't be satisfied`, async function() { + it(`should return a partial response that satisfies the request's Range: header, and an error response when it can't be satisfied`, async function () { const swURL = `${testingURL}sw.js`; await activateAndControlSW(swURL); const dummyURL = `this-file-doesnt-exist.txt`; - const partialResponseBody = await webdriver.executeAsyncScript((dummyURL, cb) => { - // Prime the cache, and then make the Range: request. - fetch(new Request(dummyURL, {headers: {Range: `bytes=5-6`}})) + const partialResponseBody = await webdriver.executeAsyncScript( + (dummyURL, cb) => { + // Prime the cache, and then make the Range: request. + fetch(new Request(dummyURL, {headers: {Range: `bytes=5-6`}})) .then((response) => response.text()) .then((text) => cb(text)) .catch((error) => cb(error.message)); - }, dummyURL); + }, + dummyURL, + ); // The values used for the byte range are inclusive, so we'll end up with // 11 characters returned in the partial response. expect(partialResponseBody).to.eql('56'); - const errorResponseStatus = await webdriver.executeAsyncScript((dummyURL, cb) => { - // These are arbitrary large values that extend past the end of the file. - fetch(new Request(dummyURL, {headers: {Range: `bytes=100-101`}})) - .then((response) => cb(response.status)); - }, dummyURL); + const errorResponseStatus = await webdriver.executeAsyncScript( + (dummyURL, cb) => { + // These are arbitrary large values that extend past the end of the file. + fetch(new Request(dummyURL, {headers: {Range: `bytes=100-101`}})).then( + (response) => cb(response.status), + ); + }, + dummyURL, + ); // The expected error status is 416 (Range Not Satisfiable) expect(errorResponseStatus).to.eql(416); diff --git a/test/workbox-range-requests/static/index.html b/test/workbox-range-requests/static/index.html index 0ea8cb448..337e4146d 100644 --- a/test/workbox-range-requests/static/index.html +++ b/test/workbox-range-requests/static/index.html @@ -1,10 +1,9 @@ - - +

    You need to manually register sw.js

    - + diff --git a/test/workbox-range-requests/static/sw.js b/test/workbox-range-requests/static/sw.js index 95fc4da3d..31443a188 100644 --- a/test/workbox-range-requests/static/sw.js +++ b/test/workbox-range-requests/static/sw.js @@ -13,19 +13,22 @@ importScripts('/__WORKBOX/buildFile/workbox-strategies'); const cacheName = 'range-requests-integration-test'; workbox.routing.registerRoute( - new RegExp('this-file-doesnt-exist\\.txt$'), - new workbox.strategies.CacheOnly({ - cacheName, - plugins: [ - new workbox.rangeRequests.RangeRequestsPlugin(), - ], - }), + new RegExp('this-file-doesnt-exist\\.txt$'), + new workbox.strategies.CacheOnly({ + cacheName, + plugins: [new workbox.rangeRequests.RangeRequestsPlugin()], + }), ); self.addEventListener('install', (event) => { self.skipWaiting(); - event.waitUntil(caches.open(cacheName).then((cache) => { - return cache.put('this-file-doesnt-exist.txt', new Response('0123456789')); - })); + event.waitUntil( + caches.open(cacheName).then((cache) => { + return cache.put( + 'this-file-doesnt-exist.txt', + new Response('0123456789'), + ); + }), + ); }); self.addEventListener('activate', () => self.clients.claim()); diff --git a/test/workbox-range-requests/sw/test-RangeRequestsPlugin.mjs b/test/workbox-range-requests/sw/test-RangeRequestsPlugin.mjs index 347baa17f..dfaeddaa7 100644 --- a/test/workbox-range-requests/sw/test-RangeRequestsPlugin.mjs +++ b/test/workbox-range-requests/sw/test-RangeRequestsPlugin.mjs @@ -8,13 +8,12 @@ import {RangeRequestsPlugin} from 'workbox-range-requests/RangeRequestsPlugin.mjs'; - -describe(`RangeRequestsPlugin`, function() { - it(`should construct with no values`, function() { +describe(`RangeRequestsPlugin`, function () { + it(`should construct with no values`, function () { new RangeRequestsPlugin(); }); - it(`should return an untouched response if there's no Range: request header`, async function() { + it(`should return an untouched response if there's no Range: request header`, async function () { const response = new Response(); const plugin = new RangeRequestsPlugin(); @@ -25,14 +24,14 @@ describe(`RangeRequestsPlugin`, function() { expect(resultResponse).to.equal(response); }); - it(`should return partial response response if there's a valid Range: request header`, async function() { + it(`should return partial response response if there's a valid Range: request header`, async function () { const response = new Response('hello, world.'); const plugin = new RangeRequestsPlugin(); const resultResponse = await plugin.cachedResponseWillBeUsed({ request: new Request('/', { headers: { - 'range': 'bytes=1-4', + range: 'bytes=1-4', }, }), cachedResponse: response, @@ -43,13 +42,13 @@ describe(`RangeRequestsPlugin`, function() { expect(responseBody).to.equal('ello'); }); - it(`should return null when the cachedResponse is null`, async function() { + it(`should return null when the cachedResponse is null`, async function () { const cachedResponse = null; const plugin = new RangeRequestsPlugin(); const resultResponse = await plugin.cachedResponseWillBeUsed({ request: new Request('/', { headers: { - 'range': 'bytes=1-4', + range: 'bytes=1-4', }, }), cachedResponse, diff --git a/test/workbox-range-requests/sw/test-createPartialResponse.mjs b/test/workbox-range-requests/sw/test-createPartialResponse.mjs index b3fdbb5ab..927b83930 100644 --- a/test/workbox-range-requests/sw/test-createPartialResponse.mjs +++ b/test/workbox-range-requests/sw/test-createPartialResponse.mjs @@ -8,8 +8,7 @@ import {createPartialResponse} from 'workbox-range-requests/createPartialResponse.mjs'; - -describe(`createPartialResponse()`, function() { +describe(`createPartialResponse()`, function () { // This uses an interface that matches what our Blob mock currently supports. // It's *not* the same way we'd use native browser implementation. function constructBlob(length) { @@ -23,63 +22,88 @@ describe(`createPartialResponse()`, function() { const SOURCE_BLOB_SIZE = 256; const SOURCE_BLOB = constructBlob(SOURCE_BLOB_SIZE); - describe(`Tests for the createPartialResponse() function`, function() { + describe(`Tests for the createPartialResponse() function`, function () { const VALID_REQUEST = new Request('/', { headers: { range: 'bytes=100-200', }, }); - it(`should return a Response with status 416 when the 'request' parameter isn't valid`, async function() { - const response = await createPartialResponse(null, new Response(SOURCE_BLOB)); + it(`should return a Response with status 416 when the 'request' parameter isn't valid`, async function () { + const response = await createPartialResponse( + null, + new Response(SOURCE_BLOB), + ); expect(response.status).to.equal(416); }); - it(`should return a Response with status 416 when the 'response' parameter isn't valid`, async function() { + it(`should return a Response with status 416 when the 'response' parameter isn't valid`, async function () { const response = await createPartialResponse(VALID_REQUEST, null); expect(response.status).to.equal(416); }); - it(`should return a Response with status 416 when there's no Range: header in the request`, async function() { + it(`should return a Response with status 416 when there's no Range: header in the request`, async function () { const noRangeHeaderRequest = new Request('/'); - const response = await createPartialResponse(noRangeHeaderRequest, new Response(SOURCE_BLOB)); + const response = await createPartialResponse( + noRangeHeaderRequest, + new Response(SOURCE_BLOB), + ); expect(response.status).to.equal(416); }); - it(`should return the expected Response when it's called with valid parameters`, async function() { - const response = await createPartialResponse(VALID_REQUEST, new Response(SOURCE_BLOB)); + it(`should return the expected Response when it's called with valid parameters`, async function () { + const response = await createPartialResponse( + VALID_REQUEST, + new Response(SOURCE_BLOB), + ); expect(response.status).to.equal(206); expect(response.headers.get('Content-Length')).to.equal('101'); - expect(response.headers.get('Content-Range')).to.equal(`bytes 100-200/${SOURCE_BLOB_SIZE}`); + expect(response.headers.get('Content-Range')).to.equal( + `bytes 100-200/${SOURCE_BLOB_SIZE}`, + ); const responseBlob = await response.blob(); const expectedBlob = constructBlob(101); - expect(await (new Response(responseBlob)).text()) - .to.equal(await (new Response(expectedBlob)).text()); + expect(await new Response(responseBlob).text()).to.equal( + await new Response(expectedBlob).text(), + ); }); - it(`should return the full body when it's called with bytes=0-`, async function() { + it(`should return the full body when it's called with bytes=0-`, async function () { const fullBodyRequest = new Request('/', { headers: { range: 'bytes=0-', }, }); - const response = await createPartialResponse(fullBodyRequest, new Response(SOURCE_BLOB)); + const response = await createPartialResponse( + fullBodyRequest, + new Response(SOURCE_BLOB), + ); expect(response.status).to.equal(206); - expect(response.headers.get('Content-Length')).to.equal(`${SOURCE_BLOB_SIZE}`); - expect(response.headers.get('Content-Range')).to.equal(`bytes 0-${SOURCE_BLOB_SIZE - 1}/${SOURCE_BLOB_SIZE}`); + expect(response.headers.get('Content-Length')).to.equal( + `${SOURCE_BLOB_SIZE}`, + ); + expect(response.headers.get('Content-Range')).to.equal( + `bytes 0-${SOURCE_BLOB_SIZE - 1}/${SOURCE_BLOB_SIZE}`, + ); const responseBlob = await response.blob(); const expectedBlob = constructBlob(SOURCE_BLOB_SIZE); - expect(await (new Response(responseBlob)).text()) - .to.equal(await (new Response(expectedBlob)).text()); + expect(await new Response(responseBlob).text()).to.equal( + await new Response(expectedBlob).text(), + ); }); - it(`should handle being passed a Response with a status of 206 by returning it as-is`, async function() { - const originalPartialResponse = new Response('expected text', {status: 206}); - const createdPartialResponse = await createPartialResponse(VALID_REQUEST, originalPartialResponse); + it(`should handle being passed a Response with a status of 206 by returning it as-is`, async function () { + const originalPartialResponse = new Response('expected text', { + status: 206, + }); + const createdPartialResponse = await createPartialResponse( + VALID_REQUEST, + originalPartialResponse, + ); // We should get back the exact same response. expect(createdPartialResponse).to.equal(originalPartialResponse); diff --git a/test/workbox-range-requests/sw/utils/test-calculateEffectiveBoundaries.mjs b/test/workbox-range-requests/sw/utils/test-calculateEffectiveBoundaries.mjs index 88ca99024..c0c8525c2 100644 --- a/test/workbox-range-requests/sw/utils/test-calculateEffectiveBoundaries.mjs +++ b/test/workbox-range-requests/sw/utils/test-calculateEffectiveBoundaries.mjs @@ -8,8 +8,7 @@ import {calculateEffectiveBoundaries} from 'workbox-range-requests/utils/calculateEffectiveBoundaries.mjs'; - -describe(`calculateEffectiveBoundaries()`, function() { +describe(`calculateEffectiveBoundaries()`, function () { function constructBlob(length) { let string = ''; for (let i = 0; i < length; i++) { @@ -21,52 +20,73 @@ describe(`calculateEffectiveBoundaries()`, function() { const SOURCE_BLOB_SIZE = 256; const SOURCE_BLOB = constructBlob(SOURCE_BLOB_SIZE); - it(`should throw when it's is called with an invalid 'blob' parameter`, async function() { + it(`should throw when it's is called with an invalid 'blob' parameter`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); const invalidBlob = null; await expectError( - () => calculateEffectiveBoundaries(invalidBlob), - 'incorrect-class', (error) => { - expect(error.details).to.have.property('moduleName', 'workbox-range-requests'); - expect(error.details).to.have.property('funcName', 'calculateEffectiveBoundaries'); - expect(error.details).to.have.property('paramName', 'blob'); - expect(error.details).to.have.property('expectedClassName', 'Blob'); - }, + () => calculateEffectiveBoundaries(invalidBlob), + 'incorrect-class', + (error) => { + expect(error.details).to.have.property( + 'moduleName', + 'workbox-range-requests', + ); + expect(error.details).to.have.property( + 'funcName', + 'calculateEffectiveBoundaries', + ); + expect(error.details).to.have.property('paramName', 'blob'); + expect(error.details).to.have.property('expectedClassName', 'Blob'); + }, ); }); - it(`should throw when it's is called with a 'start' parameter less than zero`, async function() { + it(`should throw when it's is called with a 'start' parameter less than zero`, async function () { const start = -1; const end = 1; await expectError( - () => calculateEffectiveBoundaries(SOURCE_BLOB, start, end), - 'range-not-satisfiable', + () => calculateEffectiveBoundaries(SOURCE_BLOB, start, end), + 'range-not-satisfiable', ); }); - it(`should throw when it's is called with an 'end' parameter larger than the blob's size`, async function() { + it(`should throw when it's is called with an 'end' parameter larger than the blob's size`, async function () { const start = 0; const end = SOURCE_BLOB_SIZE + 1; await expectError( - () => calculateEffectiveBoundaries(SOURCE_BLOB, start, end), - 'range-not-satisfiable', + () => calculateEffectiveBoundaries(SOURCE_BLOB, start, end), + 'range-not-satisfiable', ); }); - it(`should return the expected boundaries when it's called with valid parameters`, function() { + it(`should return the expected boundaries when it's called with valid parameters`, function () { const testCases = [ - [{start: 100, end: 200}, {start: 100, end: 201}], - [{start: undefined, end: 200}, {start: 56, end: 256}], - [{start: 100, end: undefined}, {start: 100, end: 256}], + [ + {start: 100, end: 200}, + {start: 100, end: 201}, + ], + [ + {start: undefined, end: 200}, + {start: 56, end: 256}, + ], + [ + {start: 100, end: undefined}, + {start: 100, end: 256}, + ], ]; for (const [sourceBoundaries, expectedBoundaries] of testCases) { const calculatedBoundaries = calculateEffectiveBoundaries( - SOURCE_BLOB, sourceBoundaries.start, sourceBoundaries.end); + SOURCE_BLOB, + sourceBoundaries.start, + sourceBoundaries.end, + ); - expect(expectedBoundaries).to.eql(calculatedBoundaries, - `for test case '${sourceBoundaries.start}-${sourceBoundaries.end}'`); + expect(expectedBoundaries).to.eql( + calculatedBoundaries, + `for test case '${sourceBoundaries.start}-${sourceBoundaries.end}'`, + ); } }); }); diff --git a/test/workbox-range-requests/sw/utils/test-parseRangeHeader.mjs b/test/workbox-range-requests/sw/utils/test-parseRangeHeader.mjs index 52ba7d3d8..e0524e77c 100644 --- a/test/workbox-range-requests/sw/utils/test-parseRangeHeader.mjs +++ b/test/workbox-range-requests/sw/utils/test-parseRangeHeader.mjs @@ -8,57 +8,52 @@ import {parseRangeHeader} from 'workbox-range-requests/utils/parseRangeHeader.mjs'; - -describe(`parseRangeHeader()`, function() { - it(`should throw when it's is called with an invalid 'rangeHeader' parameter`, async function() { +describe(`parseRangeHeader()`, function () { + it(`should throw when it's is called with an invalid 'rangeHeader' parameter`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); const rangeHeader = null; await expectError( - () => parseRangeHeader(rangeHeader), - 'incorrect-type', (error) => { - expect(error.details).to.have.property('moduleName', 'workbox-range-requests'); - expect(error.details).to.have.property('funcName', 'parseRangeHeader'); - expect(error.details).to.have.property('paramName', 'rangeHeader'); - expect(error.details).to.have.property('expectedType', 'string'); - }, + () => parseRangeHeader(rangeHeader), + 'incorrect-type', + (error) => { + expect(error.details).to.have.property( + 'moduleName', + 'workbox-range-requests', + ); + expect(error.details).to.have.property('funcName', 'parseRangeHeader'); + expect(error.details).to.have.property('paramName', 'rangeHeader'); + expect(error.details).to.have.property('expectedType', 'string'); + }, ); }); - it(`should throw when it's is called with a rangeHeader that doesn't start with 'bytes='`, async function() { + it(`should throw when it's is called with a rangeHeader that doesn't start with 'bytes='`, async function () { const rangeHeader = 'not-bytes='; await expectError( - () => parseRangeHeader(rangeHeader), - 'unit-must-be-bytes', + () => parseRangeHeader(rangeHeader), + 'unit-must-be-bytes', ); }); - it(`should throw when it's is called with a rangeHeader contains multiple ranges`, async function() { + it(`should throw when it's is called with a rangeHeader contains multiple ranges`, async function () { const rangeHeader = 'bytes=1-2, 3-4'; - await expectError( - () => parseRangeHeader(rangeHeader), - 'single-range-only', - ); + await expectError(() => parseRangeHeader(rangeHeader), 'single-range-only'); }); - it(`should throw when it's is called with a rangeHeader contains invalid ranges`, async function() { - const badRanges = [ - 'invalid', - '-', - 'abc-def', - '123 - 456', - ]; + it(`should throw when it's is called with a rangeHeader contains invalid ranges`, async function () { + const badRanges = ['invalid', '-', 'abc-def', '123 - 456']; for (const badRange of badRanges) { const rangeHeader = `bytes=${badRange}`; await expectError( - () => parseRangeHeader(rangeHeader), - 'invalid-range-values', + () => parseRangeHeader(rangeHeader), + 'invalid-range-values', ); } }); - it(`should return the expected start and end values when it's is called with a valid rangeHeader`, function() { + it(`should return the expected start and end values when it's is called with a valid rangeHeader`, function () { const testCases = [ ['bytes=100-200', {start: 100, end: 200}], ['bytes=-200', {start: undefined, end: 200}], @@ -67,7 +62,10 @@ describe(`parseRangeHeader()`, function() { for (const [rangeHeader, expectedValue] of testCases) { const boundaries = parseRangeHeader(rangeHeader); - expect(boundaries).to.eql(expectedValue, `for test case '${rangeHeader}'`); + expect(boundaries).to.eql( + expectedValue, + `for test case '${rangeHeader}'`, + ); } }); }); diff --git a/test/workbox-routing/integration/test-navigation-route.js b/test/workbox-routing/integration/test-navigation-route.js index fa92ec82d..358ae5441 100644 --- a/test/workbox-routing/integration/test-navigation-route.js +++ b/test/workbox-routing/integration/test-navigation-route.js @@ -10,12 +10,12 @@ const expect = require('chai').expect; const activateAndControlSW = require('../../../infra/testing/activate-and-control'); -describe(`[workbox-routing] Route via NavigationRoute`, function() { +describe(`[workbox-routing] Route via NavigationRoute`, function () { const testServerAddress = global.__workbox.server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-routing/static/routing-navigation/`; const swURL = `${testingURL}sw.js`; - it(`should load a page and route requests`, async function() { + it(`should load a page and route requests`, async function () { // Load the page and wait for the first service worker to register and activate. await global.__workbox.webdriver.get(testingURL); await activateAndControlSW(swURL); diff --git a/test/workbox-routing/integration/test-routing-basic.js b/test/workbox-routing/integration/test-routing-basic.js index e8429ce01..b056db4c0 100644 --- a/test/workbox-routing/integration/test-routing-basic.js +++ b/test/workbox-routing/integration/test-routing-basic.js @@ -10,59 +10,71 @@ const expect = require('chai').expect; const activateAndControlSW = require('../../../infra/testing/activate-and-control'); -describe(`[workbox-routing] Basic Route`, function() { +describe(`[workbox-routing] Basic Route`, function () { const testServerAddress = global.__workbox.server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-routing/static/routing-basic/`; const swURL = `${testingURL}sw.js`; - before(async function() { + before(async function () { await global.__workbox.webdriver.get(testingURL); await activateAndControlSW(swURL); }); - it(`should honor a route created by a Route object`, async function() { + it(`should honor a route created by a Route object`, async function () { const testURL = `${testServerAddress}/routeObject`; - const responseBody = await global.__workbox.webdriver.executeAsyncScript((testURL, cb) => { - fetch(testURL) + const responseBody = await global.__workbox.webdriver.executeAsyncScript( + (testURL, cb) => { + fetch(testURL) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testURL); + }, + testURL, + ); expect(responseBody).to.eql(testURL); }); - it(`should honor a same-origin route created by a string`, async function() { + it(`should honor a same-origin route created by a string`, async function () { const testURL = `${testServerAddress}/sameOrigin`; - const responseBody = await global.__workbox.webdriver.executeAsyncScript((testURL, cb) => { - fetch(testURL) + const responseBody = await global.__workbox.webdriver.executeAsyncScript( + (testURL, cb) => { + fetch(testURL) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testURL); + }, + testURL, + ); expect(responseBody).to.eql(testURL); }); - it(`should honor a cross-origin route created by a string`, async function() { + it(`should honor a cross-origin route created by a string`, async function () { const testURL = 'https://example.com/crossOrigin'; - const responseBody = await global.__workbox.webdriver.executeAsyncScript((testURL, cb) => { - fetch(testURL) + const responseBody = await global.__workbox.webdriver.executeAsyncScript( + (testURL, cb) => { + fetch(testURL) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testURL); + }, + testURL, + ); expect(responseBody).to.eql(testURL); }); - it(`should return a 404 when passed a URL that isn't routed and doesn't exist`, async function() { + it(`should return a 404 when passed a URL that isn't routed and doesn't exist`, async function () { const testURL = `${testServerAddress}/doesNotMatch`; - const responseStatus = await global.__workbox.webdriver.executeAsyncScript((testURL, cb) => { - fetch(testURL) + const responseStatus = await global.__workbox.webdriver.executeAsyncScript( + (testURL, cb) => { + fetch(testURL) .then((response) => cb(response.status)) .catch((err) => cb(err.message)); - }, testURL); + }, + testURL, + ); expect(responseStatus).to.eql(404); }); diff --git a/test/workbox-routing/integration/test-routing-regex.js b/test/workbox-routing/integration/test-routing-regex.js index 3e4e6bbea..5cf83257a 100644 --- a/test/workbox-routing/integration/test-routing-regex.js +++ b/test/workbox-routing/integration/test-routing-regex.js @@ -10,58 +10,81 @@ const expect = require('chai').expect; const activateAndControlSW = require('../../../infra/testing/activate-and-control'); -describe(`[workbox-routing] Route via RegExp`, function() { +describe(`[workbox-routing] Route via RegExp`, function () { const testServerAddress = global.__workbox.server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-routing/static/routing-regex/`; const swURL = `${testingURL}sw.js`; - it(`should load a page and route requests`, async function() { + it(`should load a page and route requests`, async function () { // Load the page and wait for the first service worker to register and activate. await global.__workbox.webdriver.get(testingURL); await activateAndControlSW(swURL); let testCounter = 0; - let response = await global.__workbox.webdriver.executeAsyncScript((testCounter, cb) => { - fetch(new URL(`/RegExp/${testCounter}/`, location).href) + let response = await global.__workbox.webdriver.executeAsyncScript( + (testCounter, cb) => { + fetch(new URL(`/RegExp/${testCounter}/`, location).href) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testCounter); + }, + testCounter, + ); - expect(response).to.equal(`RegExp.${testServerAddress}/RegExp/${testCounter}/`); + expect(response).to.equal( + `RegExp.${testServerAddress}/RegExp/${testCounter}/`, + ); testCounter += 1; - response = await global.__workbox.webdriver.executeAsyncScript((testCounter, cb) => { - fetch(new URL(`/regular-expression/${testCounter}/`, location).href) + response = await global.__workbox.webdriver.executeAsyncScript( + (testCounter, cb) => { + fetch(new URL(`/regular-expression/${testCounter}/`, location).href) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testCounter); + }, + testCounter, + ); - expect(response).to.equal(`regular-expression.${testServerAddress}/regular-expression/${testCounter}/`); + expect(response).to.equal( + `regular-expression.${testServerAddress}/regular-expression/${testCounter}/`, + ); testCounter += 1; - response = await global.__workbox.webdriver.executeAsyncScript((testCounter, cb) => { - fetch(new URL(`/RegExpRoute/RegExp/${testCounter}/`, location).href) + response = await global.__workbox.webdriver.executeAsyncScript( + (testCounter, cb) => { + fetch(new URL(`/RegExpRoute/RegExp/${testCounter}/`, location).href) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testCounter); + }, + testCounter, + ); - expect(response).to.equal(`RegExpRoute.RegExp.${testServerAddress}/RegExpRoute/RegExp/${testCounter}/`); + expect(response).to.equal( + `RegExpRoute.RegExp.${testServerAddress}/RegExpRoute/RegExp/${testCounter}/`, + ); testCounter += 1; - response = await global.__workbox.webdriver.executeAsyncScript((testCounter, cb) => { - fetch(new URL(`/RegExpRoute/regular-expression/${testCounter}/`, location).href) + response = await global.__workbox.webdriver.executeAsyncScript( + (testCounter, cb) => { + fetch( + new URL(`/RegExpRoute/regular-expression/${testCounter}/`, location) + .href, + ) .then((response) => response.text()) .then((responseBody) => cb(responseBody)) .catch((err) => cb(err.message)); - }, testCounter); + }, + testCounter, + ); - expect(response).to.equal(`RegExpRoute.regular-expression.${testServerAddress}/RegExpRoute/regular-expression/${testCounter}/`); + expect(response).to.equal( + `RegExpRoute.regular-expression.${testServerAddress}/RegExpRoute/regular-expression/${testCounter}/`, + ); }); }); diff --git a/test/workbox-routing/integration/test-sw.js b/test/workbox-routing/integration/test-sw.js index bafe6bd8a..2464530d4 100644 --- a/test/workbox-routing/integration/test-sw.js +++ b/test/workbox-routing/integration/test-sw.js @@ -8,9 +8,8 @@ const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - -describe(`[workbox-routing]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-routing]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-routing/sw/'); }); }); diff --git a/test/workbox-routing/static/routing-basic/index.html b/test/workbox-routing/static/routing-basic/index.html index 66f47fd88..7cc3d2ee9 100644 --- a/test/workbox-routing/static/routing-basic/index.html +++ b/test/workbox-routing/static/routing-basic/index.html @@ -1,6 +1,5 @@ - - +

    You need to manually register sw.js

    diff --git a/test/workbox-routing/static/routing-basic/sw.js b/test/workbox-routing/static/routing-basic/sw.js index 406d5f968..ce54d9e0b 100644 --- a/test/workbox-routing/static/routing-basic/sw.js +++ b/test/workbox-routing/static/routing-basic/sw.js @@ -14,20 +14,14 @@ importScripts('/__WORKBOX/buildFile/workbox-routing'); const handler = ({url}) => new Response(url); const routeObject = new workbox.routing.Route( - ({url}) => url.pathname === '/routeObject', - handler, + ({url}) => url.pathname === '/routeObject', + handler, ); workbox.routing.registerRoute(routeObject); -workbox.routing.registerRoute( - '/sameOrigin', - handler, -); +workbox.routing.registerRoute('/sameOrigin', handler); -workbox.routing.registerRoute( - 'https://example.com/crossOrigin', - handler, -); +workbox.routing.registerRoute('https://example.com/crossOrigin', handler); self.addEventListener('install', () => self.skipWaiting()); self.addEventListener('activate', () => self.clients.claim()); diff --git a/test/workbox-routing/static/routing-navigation/index.html b/test/workbox-routing/static/routing-navigation/index.html index 2fa6d40ea..7cc3d2ee9 100644 --- a/test/workbox-routing/static/routing-navigation/index.html +++ b/test/workbox-routing/static/routing-navigation/index.html @@ -1,7 +1,6 @@ - - +

    You need to manually register sw.js

    - + diff --git a/test/workbox-routing/static/routing-navigation/sw.js b/test/workbox-routing/static/routing-navigation/sw.js index 0831b6f23..e7dfa4272 100644 --- a/test/workbox-routing/static/routing-navigation/sw.js +++ b/test/workbox-routing/static/routing-navigation/sw.js @@ -10,12 +10,14 @@ importScripts('/__WORKBOX/buildFile/workbox-core'); importScripts('/__WORKBOX/buildFile/workbox-routing'); workbox.routing.registerRoute( - new workbox.routing.NavigationRoute( - ({url}) => { - return new Response(`NavigationRoute.${url.href}`); - }, - ), + new workbox.routing.NavigationRoute(({url}) => { + return new Response(`NavigationRoute.${url.href}`); + }), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-routing/static/routing-regex/index.html b/test/workbox-routing/static/routing-regex/index.html index 6dda8f265..9996b2d2a 100644 --- a/test/workbox-routing/static/routing-regex/index.html +++ b/test/workbox-routing/static/routing-regex/index.html @@ -1,8 +1,7 @@ - - +

    Workbox Routing - routing-regex

    You need to manually register sw.js

    - + diff --git a/test/workbox-routing/static/routing-regex/sw.js b/test/workbox-routing/static/routing-regex/sw.js index 8ad29d739..aaab96d9d 100644 --- a/test/workbox-routing/static/routing-regex/sw.js +++ b/test/workbox-routing/static/routing-regex/sw.js @@ -10,36 +10,34 @@ importScripts('/__WORKBOX/buildFile/workbox-core'); importScripts('/__WORKBOX/buildFile/workbox-routing'); workbox.routing.registerRoute( - new workbox.routing.RegExpRoute( - new RegExp('/RegExpRoute/RegExp/.*/'), - ({url}) => { - return new Response(`RegExpRoute.RegExp.${url.href}`); - }, - ), -); - -workbox.routing.registerRoute( - new workbox.routing.RegExpRoute( - new RegExp('/RegExpRoute/regular-expression/.*/'), - ({url}) => { - return new Response(`RegExpRoute.regular-expression.${url.href}`); - }, - ), -); - -workbox.routing.registerRoute( - new RegExp('/RegExp/.*/'), + new workbox.routing.RegExpRoute( + new RegExp('/RegExpRoute/RegExp/.*/'), ({url}) => { - return new Response(`RegExp.${url.href}`); + return new Response(`RegExpRoute.RegExp.${url.href}`); }, + ), ); workbox.routing.registerRoute( - /\/regular-expression\/.*\//, + new workbox.routing.RegExpRoute( + new RegExp('/RegExpRoute/regular-expression/.*/'), ({url}) => { - return new Response(`regular-expression.${url.href}`); + return new Response(`RegExpRoute.regular-expression.${url.href}`); }, + ), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +workbox.routing.registerRoute(new RegExp('/RegExp/.*/'), ({url}) => { + return new Response(`RegExp.${url.href}`); +}); + +workbox.routing.registerRoute(/\/regular-expression\/.*\//, ({url}) => { + return new Response(`regular-expression.${url.href}`); +}); + +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-routing/static/routing.html b/test/workbox-routing/static/routing.html index e5734650f..80cd29443 100644 --- a/test/workbox-routing/static/routing.html +++ b/test/workbox-routing/static/routing.html @@ -1,17 +1,20 @@ - - - - - -

    Get Routing Replacing an Image.

    + + + + + +

    Get Routing Replacing an Image.

    - - + + - - + + diff --git a/test/workbox-routing/static/sw.js b/test/workbox-routing/static/sw.js index b31378502..6235d6a78 100644 --- a/test/workbox-routing/static/sw.js +++ b/test/workbox-routing/static/sw.js @@ -6,16 +6,29 @@ https://opensource.org/licenses/MIT. */ -importScripts('../../../../packages/workbox-core/build/browser/workbox-core.dev.js'); -importScripts('../../../../packages/workbox-routing/build/browser/workbox-routing.dev.js'); +importScripts( + '../../../../packages/workbox-core/build/browser/workbox-core.dev.js', +); +importScripts( + '../../../../packages/workbox-routing/build/browser/workbox-routing.dev.js', +); const routing = self.workbox.routing; const Route = self.workbox.routing.Route; -const specialImgURL = new URL('/test/workbox-routing/static/demo-img.png', location).toString(); -const specialImgRoute = new Route(({event}) => { - return (event.request.url === specialImgURL); -}, ()=> { - return fetch('http://via.placeholder.com/300x300/ffffff/F57C00?text=Hello+from+Workbox', {mode: 'no-cors'}); -}); +const specialImgURL = new URL( + '/test/workbox-routing/static/demo-img.png', + location, +).toString(); +const specialImgRoute = new Route( + ({event}) => { + return event.request.url === specialImgURL; + }, + () => { + return fetch( + 'http://via.placeholder.com/300x300/ffffff/F57C00?text=Hello+from+Workbox', + {mode: 'no-cors'}, + ); + }, +); routing.registerRoute(specialImgRoute); diff --git a/test/workbox-routing/sw/test-NavigationRoute.mjs b/test/workbox-routing/sw/test-NavigationRoute.mjs index 37f0ef49b..1ec8c7a28 100644 --- a/test/workbox-routing/sw/test-NavigationRoute.mjs +++ b/test/workbox-routing/sw/test-NavigationRoute.mjs @@ -8,7 +8,6 @@ import {NavigationRoute} from 'workbox-routing/NavigationRoute.mjs'; - const handler = { handle: () => {}, }; @@ -16,47 +15,63 @@ const functionHandler = () => {}; const invalidHandlerObject = {}; -describe(`NavigationRoute`, function() { - 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', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => new NavigationRoute(), + 'incorrect-type', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); await expectError( - () => new NavigationRoute(invalidHandlerObject), - 'missing-a-method', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => new NavigationRoute(invalidHandlerObject), + 'missing-a-method', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); }); - it(`should not throw when called with valid handler in dev`, function() { + it(`should not throw when called with valid handler in dev`, function () { expect(() => new NavigationRoute(handler)).not.to.throw(); }); - it(`should not throw when called with a valid function handler`, function() { + it(`should not throw when called with a valid function handler`, function () { expect(() => new NavigationRoute(functionHandler)).not.to.throw(); }); - it(`should have a HTTP method of 'GET'`, async function() { + it(`should have a HTTP method of 'GET'`, async function () { const route = new NavigationRoute(handler); expect(route.method).to.equal('GET'); }); - it(`should match all navigation requests by default`, function() { + it(`should match all navigation requests by default`, function () { const urls = [ new URL('/', self.location).toString(), new URL('/testing/path.html', self.location).toString(), @@ -70,7 +85,7 @@ describe(`NavigationRoute`, function() { }); }); - it(`should not match non- navigation requests by default`, function() { + it(`should not match non- navigation requests by default`, function () { const urls = [ new URL('/', self.location), new URL('/testing/path.html', self.location), @@ -82,7 +97,7 @@ describe(`NavigationRoute`, function() { }); }); - it(`should not include urls in denylist that completely match`, function() { + it(`should not include urls in denylist that completely match`, function () { const url = new URL('/testing/path.html', self.location); const request = new Request(url); Object.defineProperty(request, 'mode', {value: 'navigate'}); @@ -94,7 +109,7 @@ describe(`NavigationRoute`, function() { expect(navigationRoute.match({request, url})).to.equal(false); }); - it(`should denylist urls with search params that result in partial match with regex`, function() { + it(`should denylist urls with search params that result in partial match with regex`, function () { const url = new URL('/testing/path.html?test=hello', self.location); const request = new Request(url); Object.defineProperty(request, 'mode', {value: 'navigate'}); @@ -106,7 +121,7 @@ describe(`NavigationRoute`, function() { expect(navigationRoute.match({request, url})).to.equal(false); }); - it(`should only match urls in custom allowlist`, function() { + it(`should only match urls in custom allowlist`, function () { let url = new URL('/testing/path.html?test=hello', self.location); let request = new Request(url); Object.defineProperty(request, 'mode', {value: 'navigate'}); @@ -124,7 +139,7 @@ describe(`NavigationRoute`, function() { expect(navigationRoute.match({request, url})).to.equal(false); }); - it(`should take denylist as priority`, function() { + it(`should take denylist as priority`, function () { let url = new URL('/testing/path.html?test=hello', self.location); let request = new Request(url); Object.defineProperty(request, 'mode', {value: 'navigate'}); diff --git a/test/workbox-routing/sw/test-RegExpRoute.mjs b/test/workbox-routing/sw/test-RegExpRoute.mjs index 709030481..cf5f446a1 100644 --- a/test/workbox-routing/sw/test-RegExpRoute.mjs +++ b/test/workbox-routing/sw/test-RegExpRoute.mjs @@ -8,44 +8,53 @@ import {RegExpRoute} from 'workbox-routing/RegExpRoute.mjs'; - -describe(`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'; const HANDLER = {handle: () => {}}; const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); sandbox.stub(self, 'location').value(SAME_ORIGIN_URL); }); - after(function() { + after(function () { sandbox.restore(); }); for (const badRegExp of [undefined, null, 123, '123', {}]) { - 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', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('RegExpRoute'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('pattern'); - }, + () => new RegExpRoute(), + 'incorrect-class', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('RegExpRoute'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('pattern'); + }, ); }); } - it(`should not throw when called with valid parameters`, function() { + it(`should not throw when called with valid parameters`, function () { expect(() => new RegExpRoute(new RegExp('/test/'), HANDLER)).not.to.throw(); }); - it(`should properly match URLs`, function() { + it(`should properly match URLs`, function () { const matchingURL = new URL(PATH, SAME_ORIGIN_URL); const nonMatchingURL = new URL('/does/not/match', SAME_ORIGIN_URL); const crossOriginURL = new URL(PATH, CROSS_ORIGIN_URL); @@ -59,16 +68,23 @@ describe(`RegExpRoute`, function() { expect(route.match({url: crossOriginURL})).not.to.be.ok; }); - it(`should properly match cross-origin URLs with wildcards`, function() { - const matchingURL = new URL('https://fonts.googleapis.com/icon?family=Material+Icons'); - const matchingURL2 = new URL('https://code.getmdl.io/1.2.1/material.indigo-pink.min.css'); - - const route = new RegExpRoute(/.*\.(?:googleapis|getmdl)\.(?:com|io)\/.*/, HANDLER); + it(`should properly match cross-origin URLs with wildcards`, function () { + const matchingURL = new URL( + 'https://fonts.googleapis.com/icon?family=Material+Icons', + ); + const matchingURL2 = new URL( + 'https://code.getmdl.io/1.2.1/material.indigo-pink.min.css', + ); + + const route = new RegExpRoute( + /.*\.(?:googleapis|getmdl)\.(?:com|io)\/.*/, + HANDLER, + ); expect(route.match({url: matchingURL})).to.be.ok; expect(route.match({url: matchingURL2})).to.be.ok; }); - it(`should properly match cross-origin URLs without wildcards`, function() { + it(`should properly match cross-origin URLs without wildcards`, function () { const matchingURL = new URL(PATH, CROSS_ORIGIN_URL); const nonMatchingURL = new URL('/does/not/match', CROSS_ORIGIN_URL); const crossOriginRegExp = new RegExp(matchingURL.href); @@ -78,13 +94,19 @@ describe(`RegExpRoute`, function() { expect(route.match({url: nonMatchingURL})).not.to.be.ok; }); - it(`should properly match URLs with capture groups`, function() { + it(`should properly match URLs with capture groups`, function () { const value1 = 'value1'; const value2 = 'value2'; const captureGroupRegExp = new RegExp('/(\\w+)/dummy/(\\w+)'); - const captureGroupMatchingURL = new URL(`/${value1}/dummy/${value2}`, SAME_ORIGIN_URL); - const captureGroupNonMatchingURL = new URL(`/${value1}/${value2}`, SAME_ORIGIN_URL); + const captureGroupMatchingURL = new URL( + `/${value1}/dummy/${value2}`, + SAME_ORIGIN_URL, + ); + const captureGroupNonMatchingURL = new URL( + `/${value1}/${value2}`, + SAME_ORIGIN_URL, + ); const route = new RegExpRoute(captureGroupRegExp, HANDLER); diff --git a/test/workbox-routing/sw/test-Route.mjs b/test/workbox-routing/sw/test-Route.mjs index ea7f7f787..2eef520e0 100644 --- a/test/workbox-routing/sw/test-Route.mjs +++ b/test/workbox-routing/sw/test-Route.mjs @@ -8,7 +8,6 @@ import {Route} from 'workbox-routing/Route.mjs'; - const match = () => {}; const handler = { handle: () => {}, @@ -19,119 +18,151 @@ const method = 'POST'; const invalidHandlerObject = {}; const invalidMethod = 'INVALID'; -describe(`Route`, function() { - it(`should throw when called without any parameters in dev`, async 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(); await expectError( - () => new Route(), - 'incorrect-type', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - }, + () => new Route(), + 'incorrect-type', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + }, ); }); - it(`should throw when called without a valid handler parameter in dev`, async function() { + it(`should throw when called without a valid handler parameter in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); await expectError( - () => new Route(match), - 'incorrect-type', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => new Route(match), + 'incorrect-type', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); await expectError( - () => new Route(match, invalidHandlerObject), - 'missing-a-method', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => new Route(match, invalidHandlerObject), + 'missing-a-method', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); }); - it(`should throw when called without a valid match parameter in dev`, async function() { + it(`should throw when called without a valid match parameter in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); await expectError( - () => new Route(null, handler), - 'incorrect-type', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('match'); - }, + () => new Route(null, handler), + 'incorrect-type', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('match'); + }, ); }); - it(`should not throw when called with valid handler.handle and match parameters in dev`, function() { + it(`should not throw when called with valid handler.handle and match parameters in dev`, function () { if (process.env.NODE_ENV === 'production') return this.skip(); expect(() => new Route(match, handler)).not.to.throw(); }); - it(`should not throw when called with a valid function handler and match parameters in dev`, function() { + it(`should not throw when called with a valid function handler and match parameters in dev`, function () { if (process.env.NODE_ENV === 'production') return this.skip(); expect(() => new Route(match, functionHandler)).not.to.throw(); }); - it(`should throw when called with an invalid method in dev`, async function() { + it(`should throw when called with an invalid method in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); await expectError( - () => new Route(match, handler, invalidMethod), - 'invalid-value', - (error) => expect(error.details).to.have.property('paramName').that.equals('method'), + () => new Route(match, handler, invalidMethod), + 'invalid-value', + (error) => + expect(error.details) + .to.have.property('paramName') + .that.equals('method'), ); }); - it(`should use the method provided when called with a valid method in dev`, function() { + it(`should use the method provided when called with a valid method in dev`, function () { if (process.env.NODE_ENV === 'production') return this.skip(); const route = new Route(match, handler, method); expect(route.method).to.equal(method); }); - it(`should use a default of GET when called without a method in dev`, function() { + it(`should use a default of GET when called without a method in dev`, function () { if (process.env.NODE_ENV === 'production') return this.skip(); const route = new Route(match, handler); expect(route.method).to.equal('GET'); }); - - it(`should not throw when called with valid handler.handle and match parameters in production`, function() { + it(`should not throw when called with valid handler.handle and match parameters in production`, function () { if (process.env.NODE_ENV !== 'production') return this.skip(); expect(() => new Route(match, handler)).not.to.throw(); }); - it(`should not throw when called with a valid function handler and match parameters in production`, function() { + it(`should not throw when called with a valid function handler and match parameters in production`, function () { if (process.env.NODE_ENV !== 'production') return this.skip(); expect(() => new Route(match, functionHandler)).not.to.throw(); }); - it(`should use the method provided when called with a valid method in production`, function() { + it(`should use the method provided when called with a valid method in production`, function () { if (process.env.NODE_ENV !== 'production') return this.skip(); const route = new Route(match, handler, method); expect(route.method).to.equal(method); }); - it(`should use a default of GET when called without a method in production`, function() { + it(`should use a default of GET when called without a method in production`, function () { if (process.env.NODE_ENV !== 'production') return this.skip(); const route = new Route(match, handler); diff --git a/test/workbox-routing/sw/test-Router.mjs b/test/workbox-routing/sw/test-Router.mjs index 08367f67a..103cdc9ee 100644 --- a/test/workbox-routing/sw/test-Router.mjs +++ b/test/workbox-routing/sw/test-Router.mjs @@ -13,108 +13,193 @@ import {logger} from 'workbox-core/_private/logger.mjs'; import {dispatchAndWaitUntilDone} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import generateTestVariants from '../../../infra/testing/generate-variant-tests'; - -describe(`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() { + beforeEach(async function () { sandbox.restore(); // Spy on all added event listeners so they can be removed. sandbox.spy(self, 'addEventListener'); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - describe(`constructor`, function() { - it(`should construct without any inputs`, function() { + describe(`constructor`, function () { + it(`should construct without any inputs`, function () { expect(() => { new Router(); }).to.not.throw(); }); }); - describe(`registerRoute()`, function() { - const invalidMatches = [{}, true, false, 123, '123', [123], null, undefined]; - generateTestVariants(`should throw in dev when route.match is not a function`, invalidMatches, async function(variant) { - if (process.env.NODE_ENV === 'production') return this.skip(); - - const router = new Router(); - await expectError( - () => router.registerRoute({handler: HANDLER, method: METHOD, match: variant}), + describe(`registerRoute()`, function () { + const invalidMatches = [ + {}, + true, + false, + 123, + '123', + [123], + null, + undefined, + ]; + generateTestVariants( + `should throw in dev when route.match is not a function`, + invalidMatches, + async function (variant) { + if (process.env.NODE_ENV === 'production') return this.skip(); + + const router = new Router(); + await expectError( + () => + router.registerRoute({ + handler: HANDLER, + method: METHOD, + match: variant, + }), 'missing-a-method', (error) => { - expect(error.details).to.have.property('moduleName').that.eql('workbox-routing'); - expect(error.details).to.have.property('className').that.eql('Router'); - expect(error.details).to.have.property('funcName').that.eql('registerRoute'); - expect(error.details).to.have.property('paramName').that.eql('route'); - expect(error.details).to.have.property('expectedMethod').that.eql('match'); - }); - }); + expect(error.details) + .to.have.property('moduleName') + .that.eql('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.eql('Router'); + expect(error.details) + .to.have.property('funcName') + .that.eql('registerRoute'); + expect(error.details) + .to.have.property('paramName') + .that.eql('route'); + expect(error.details) + .to.have.property('expectedMethod') + .that.eql('match'); + }, + ); + }, + ); const invalidHandlers = [() => {}, true, false, 123, '123', undefined]; - generateTestVariants(`should throw in dev when route.handler is not an object`, invalidHandlers, async function(variant) { - if (process.env.NODE_ENV == 'production') return this.skip(); - - const router = new Router(); - await expectError( - () => router.registerRoute({match: MATCH, method: METHOD, handler: variant}), + generateTestVariants( + `should throw in dev when route.handler is not an object`, + invalidHandlers, + async function (variant) { + if (process.env.NODE_ENV == 'production') return this.skip(); + + const router = new Router(); + await expectError( + () => + router.registerRoute({ + match: MATCH, + method: METHOD, + handler: variant, + }), 'incorrect-type', (error) => { - expect(error.details).to.have.property('moduleName').that.eql('workbox-routing'); - expect(error.details).to.have.property('className').that.eql('Router'); - expect(error.details).to.have.property('funcName').that.eql('registerRoute'); - expect(error.details).to.have.property('paramName').that.eql('route'); - expect(error.details).to.have.property('expectedType').that.eql('object'); + expect(error.details) + .to.have.property('moduleName') + .that.eql('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.eql('Router'); + expect(error.details) + .to.have.property('funcName') + .that.eql('registerRoute'); + expect(error.details) + .to.have.property('paramName') + .that.eql('route'); + expect(error.details) + .to.have.property('expectedType') + .that.eql('object'); }, - ); - }); - - const invalidMethods = [() => {}, {}, true, false, 123, [123], null, undefined]; - generateTestVariants(`should throw in dev when route.method is not a string`, invalidMethods, async function(variant) { - if (process.env.NODE_ENV == 'production') return this.skip(); - - const router = new Router(); - await expectError( - () => router.registerRoute({match: MATCH, handler: HANDLER, method: variant}), + ); + }, + ); + + const invalidMethods = [ + () => {}, + {}, + true, + false, + 123, + [123], + null, + undefined, + ]; + generateTestVariants( + `should throw in dev when route.method is not a string`, + invalidMethods, + async function (variant) { + if (process.env.NODE_ENV == 'production') return this.skip(); + + const router = new Router(); + await expectError( + () => + router.registerRoute({ + match: MATCH, + handler: HANDLER, + method: variant, + }), 'incorrect-type', (error) => { - expect(error.details).to.have.property('moduleName').that.eql('workbox-routing'); - expect(error.details).to.have.property('className').that.eql('Router'); - expect(error.details).to.have.property('funcName').that.eql('registerRoute'); - expect(error.details).to.have.property('paramName').that.eql('route.method'); - expect(error.details).to.have.property('expectedType').that.eql('string'); + expect(error.details) + .to.have.property('moduleName') + .that.eql('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.eql('Router'); + expect(error.details) + .to.have.property('funcName') + .that.eql('registerRoute'); + expect(error.details) + .to.have.property('paramName') + .that.eql('route.method'); + expect(error.details) + .to.have.property('expectedType') + .that.eql('string'); }, - ); - }); + ); + }, + ); - it(`should throw in dev when route.handler.handle is not a function`, async function() { + it(`should throw in dev when route.handler.handle is not a function`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); const router = new Router(); await expectError( - () => router.registerRoute({match: MATCH, method: METHOD, handler: {}}), - 'missing-a-method', - (error) => { - expect(error.details).to.have.property('moduleName').that.eql('workbox-routing'); - expect(error.details).to.have.property('className').that.eql('Router'); - expect(error.details).to.have.property('funcName').that.eql('registerRoute'); - expect(error.details).to.have.property('paramName').that.eql('route.handler'); - expect(error.details).to.have.property('expectedMethod').that.eql('handle'); - }, + () => router.registerRoute({match: MATCH, method: METHOD, handler: {}}), + 'missing-a-method', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.eql('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.eql('Router'); + expect(error.details) + .to.have.property('funcName') + .that.eql('registerRoute'); + expect(error.details) + .to.have.property('paramName') + .that.eql('route.handler'); + expect(error.details) + .to.have.property('expectedMethod') + .that.eql('handle'); + }, ); }); - it(`should add the expected entries to the internal arrays of routes`, function() { + it(`should add the expected entries to the internal arrays of routes`, function () { const router = new Router(); // Routes without an explicit method will default to GET. @@ -129,7 +214,13 @@ describe(`Router`, function() { method: 'POST', }; - for (const route of [getRoute1, getRoute2, putRoute1, putRoute2, postRoute]) { + for (const route of [ + getRoute1, + getRoute2, + putRoute1, + putRoute2, + postRoute, + ]) { router.registerRoute(route); } @@ -139,12 +230,13 @@ describe(`Router`, function() { }); }); - describe(`addFetchListener`, function() { - it(`should add a listener to respond to fetch events`, async function() { + describe(`addFetchListener`, function () { + it(`should add a listener to respond to fetch events`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY)); + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), + ); router.registerRoute(route); router.addFetchListener(); @@ -164,11 +256,12 @@ describe(`Router`, function() { expect(await response.text()).to.equal(EXPECTED_RESPONSE_BODY); }); - it(`should not call respondWith when no routes match`, async 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)); + () => false, + () => new Response(EXPECTED_RESPONSE_BODY), + ); router.registerRoute(route); router.addFetchListener(); @@ -184,12 +277,13 @@ describe(`Router`, function() { }); }); - describe(`addCacheListener`, function() { - it(`should add a listener to respond to cache message events`, async function() { + describe(`addCacheListener`, function () { + it(`should add a listener to respond to cache message events`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY)); + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), + ); router.registerRoute(route); router.addCacheListener(); @@ -208,49 +302,61 @@ describe(`Router`, function() { 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(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(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() { + it(`should accept URL strings or request URL+requestInit tuples`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY)); + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), + ); router.registerRoute(route); router.addCacheListener(); sandbox.spy(router, 'handleRequest'); - await dispatchAndWaitUntilDone(new ExtendableMessageEvent('message', { - data: { - type: 'CACHE_URLS', - payload: { - urlsToCache: [ - '/one', - ['/two', {mode: 'no-cors'}], - '/three', - ], + await dispatchAndWaitUntilDone( + new ExtendableMessageEvent('message', { + data: { + type: 'CACHE_URLS', + payload: { + urlsToCache: ['/one', ['/two', {mode: 'no-cors'}], '/three'], + }, }, - }, - })); + }), + ); 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[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[1][0].request.mode).to.equal('no-cors'); - expect(router.handleRequest.args[2][0].request.url).to.equal(`${location.origin}/three`); + expect(router.handleRequest.args[2][0].request.url).to.equal( + `${location.origin}/three`, + ); }); - it(`should do nothing for non CACHE_URLS message types`, async function() { + it(`should do nothing for non CACHE_URLS message types`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY)); + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), + ); router.registerRoute(route); router.addCacheListener(); @@ -262,8 +368,8 @@ describe(`Router`, function() { }); }); - describe(`unregisterRoute()`, function() { - it(`should remove the expected entries from the internal arrays of routes`, function() { + describe(`unregisterRoute()`, function () { + it(`should remove the expected entries from the internal arrays of routes`, function () { const router = new Router(); // Routes without an explicit method will default to GET. @@ -278,7 +384,13 @@ describe(`Router`, function() { method: 'POST', }; - for (const route of [getRoute1, getRoute2, putRoute1, putRoute2, postRoute]) { + for (const route of [ + getRoute1, + getRoute2, + putRoute1, + putRoute2, + postRoute, + ]) { router.registerRoute(route); } @@ -290,7 +402,7 @@ describe(`Router`, function() { expect(router.routes.get('POST')).to.have.members([postRoute]); }); - it(`should throw when called with a route with a method for which there isn't an array of routes`, function() { + it(`should throw when called with a route with a method for which there isn't an array of routes`, function () { const router = new Router(); // Routes without an explicit method will default to GET. @@ -299,15 +411,15 @@ describe(`Router`, function() { router.registerRoute(getRoute); return expectError( - () => router.unregisterRoute(putRoute), - 'unregister-route-but-not-found-with-method', - (error) => { - expect(error.details).to.have.property('method').that.eql('PUT'); - }, + () => router.unregisterRoute(putRoute), + 'unregister-route-but-not-found-with-method', + (error) => { + expect(error.details).to.have.property('method').that.eql('PUT'); + }, ); }); - it(`should throw when called with a route that wasn't previously registered`, function() { + it(`should throw when called with a route that wasn't previously registered`, function () { const router = new Router(); // Routes without an explicit method will default to GET. @@ -316,21 +428,21 @@ describe(`Router`, function() { router.registerRoute(getRoute1); return expectError( - () => router.unregisterRoute(getRoute2), - 'unregister-route-route-not-registered', + () => router.unregisterRoute(getRoute2), + 'unregister-route-route-not-registered', ); }); }); - describe(`setDefaultHandler()`, function() { - it(`should update the expected internal state, with the default method`, function() { + describe(`setDefaultHandler()`, function () { + it(`should update the expected internal state, with the default method`, function () { const router = new Router(); router.setDefaultHandler(HANDLER); expect(router._defaultHandlerMap.get('GET')).to.eql(HANDLER); }); - it(`should update the expected internal state, with specific methods`, function() { + it(`should update the expected internal state, with specific methods`, function () { const router = new Router(); router.setDefaultHandler(HANDLER, 'POST'); router.setDefaultHandler(HANDLER, 'PUT'); @@ -340,11 +452,11 @@ describe(`Router`, function() { expect(router._defaultHandlerMap.get('GET')).to.not.exist; }); - it(`should return a response from the default handler when there's no matching route`, async function() { + it(`should return a response from the default handler when there's no matching route`, async function () { const router = new Router(); const route = new Route( - () => false, - () => new Response(), + () => false, + () => new Response(), ); router.registerRoute(route); router.setDefaultHandler(() => new Response(EXPECTED_RESPONSE_BODY)); @@ -359,14 +471,17 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should return a response from the default handler when there's no matching route, for a custom method`, async function() { + it(`should return a response from the default handler when there's no matching route, for a custom method`, async function () { const router = new Router(); const route = new Route( - () => false, - () => new Response(), + () => false, + () => new Response(), ); router.registerRoute(route); - router.setDefaultHandler(() => new Response(EXPECTED_RESPONSE_BODY), 'POST'); + router.setDefaultHandler( + () => new Response(EXPECTED_RESPONSE_BODY), + 'POST', + ); const postRequest = new Request(location, {method: 'POST'}); const postEvent = new FetchEvent('fetch', {request: postRequest}); @@ -388,19 +503,19 @@ describe(`Router`, function() { }); }); - describe(`setCatchHandler()`, function() { - it(`should update the expected internal state`, function() { + describe(`setCatchHandler()`, function () { + it(`should update the expected internal state`, function () { const router = new Router(); router.setCatchHandler(HANDLER); expect(router._catchHandler).to.deep.eql(HANDLER); }); - it(`should return a response from the catch handler when the matching route's handler rejects async`, async function() { + it(`should return a response from the catch handler when the matching route's handler rejects async`, async function () { const router = new Router(); const route = new Route( - () => true, - () => Promise.reject(new Error()), + () => true, + () => Promise.reject(new Error()), ); router.registerRoute(route); router.setCatchHandler(() => new Response(EXPECTED_RESPONSE_BODY)); @@ -414,13 +529,13 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should return a response from the catch handler when the matching route's handler throws sync`, async function() { + it(`should return a response from the catch handler when the matching route's handler throws sync`, async function () { const router = new Router(); const route = new Route( - () => true, - () => { - throw new Error(`Injected sync error`); - }, + () => true, + () => { + throw new Error(`Injected sync error`); + }, ); router.registerRoute(route); router.setCatchHandler(() => new Response(EXPECTED_RESPONSE_BODY)); @@ -435,8 +550,8 @@ describe(`Router`, function() { }); }); - describe(`handleRequest()`, function() { - it(`should throw in dev when not passed a request`, async function() { + describe(`handleRequest()`, function () { + it(`should throw in dev when not passed a request`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); const router = new Router(); @@ -444,21 +559,30 @@ describe(`Router`, function() { const event = new FetchEvent('fetch', {request}); await expectError( - () => router.handleRequest({event}), - 'incorrect-class', - (error) => { - expect(error.details).to.have.property('moduleName').that.eql('workbox-routing'); - expect(error.details).to.have.property('className').that.eql('Router'); - expect(error.details).to.have.property('funcName').that.eql('handleRequest'); - expect(error.details).to.have.property('paramName').that.eql('options.request'); - }); + () => router.handleRequest({event}), + 'incorrect-class', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.eql('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.eql('Router'); + expect(error.details) + .to.have.property('funcName') + .that.eql('handleRequest'); + expect(error.details) + .to.have.property('paramName') + .that.eql('options.request'); + }, + ); }); - it(`should return a response from the Route's handler when there's a matching route`, async function() { + it(`should return a response from the Route's handler when there's a matching route`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY), + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), ); router.registerRoute(route); @@ -471,11 +595,11 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should fall back to the Route's catch handler if there's an error in the Route's handler, if set`, async function() { + it(`should fall back to the Route's catch handler if there's an error in the Route's handler, if set`, async function () { const router = new Router(); const route = new Route( - () => true, - () => Promise.reject(new Error()), + () => true, + () => Promise.reject(new Error()), ); route.setCatchHandler(() => new Response(EXPECTED_RESPONSE_BODY)); router.registerRoute(route); @@ -489,11 +613,11 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should fall back to the global catch handler if there's an error in the Route's catch handler`, async function() { + it(`should fall back to the global catch handler if there's an error in the Route's catch handler`, async function () { const router = new Router(); const route = new Route( - () => true, - () => Promise.reject(new Error()), + () => true, + () => Promise.reject(new Error()), ); route.setCatchHandler(() => Promise.reject(new Error())); router.setCatchHandler(() => new Response(EXPECTED_RESPONSE_BODY)); @@ -508,18 +632,18 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should return a response from the first matching route when there are multiple potential matches`, async function() { + it(`should return a response from the first matching route when there are multiple potential matches`, async function () { const router = new Router(); const response1 = 'response1'; const response2 = 'response2'; const route1 = new Route( - () => true, - () => new Response(response1), + () => true, + () => new Response(response1), ); router.registerRoute(route1); const route2 = new Route( - () => true, - () => new Response(response2), + () => true, + () => new Response(response2), ); router.registerRoute(route2); @@ -532,11 +656,11 @@ describe(`Router`, function() { expect(responseBody).to.eql(response1); }); - it(`should work when no event is passed`, async function() { + it(`should work when no event is passed`, async function () { const router = new Router(); const route = new Route( - () => true, - () => new Response(EXPECTED_RESPONSE_BODY), + () => true, + () => new Response(EXPECTED_RESPONSE_BODY), ); router.registerRoute(route); @@ -548,16 +672,16 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should work when request and event.request are different`, async function() { + it(`should work when request and event.request are different`, async function () { const router = new Router(); const route = new Route( - () => true, - ({url}) => { - // Ensure request (not event.request) is passed to the handler. - if (url.href !== 'https://unexpected.com') { - return new Response(EXPECTED_RESPONSE_BODY); - } - }, + () => true, + ({url}) => { + // Ensure request (not event.request) is passed to the handler. + if (url.href !== 'https://unexpected.com') { + return new Response(EXPECTED_RESPONSE_BODY); + } + }, ); router.registerRoute(route); @@ -572,11 +696,11 @@ describe(`Router`, function() { expect(responseBody).to.eql(EXPECTED_RESPONSE_BODY); }); - it(`should not return a response when there's no matching route and no default handler`, async function() { + it(`should not return a response when there's no matching route and no default handler`, async function () { const router = new Router(); const route = new Route( - () => false, - () => new Response(), + () => false, + () => new Response(), ); router.registerRoute(route); @@ -588,7 +712,7 @@ describe(`Router`, function() { expect(response).not.to.exist; }); - it(`should not respond to non-http requests`, function() { + it(`should not respond to non-http requests`, function () { const router = new Router(); // route.match() always returns false, so the Request details don't matter. @@ -599,11 +723,14 @@ describe(`Router`, function() { expect(response).not.to.exist; }); - it(`should invoke route handlers with the correct arguments`, async function() { + it(`should invoke route handlers with the correct arguments`, async function () { const router = new Router(); - const match = sandbox.stub() - .onCall(0).returns(true) - .onCall(1).returns([1, 2, 3]); + const match = sandbox + .stub() + .onCall(0) + .returns(true) + .onCall(1) + .returns([1, 2, 3]); const handler = sandbox.stub().returns(new Response()); @@ -630,24 +757,30 @@ describe(`Router`, function() { }); const matchCallbackReturnValues = [{a: 'b'}, [1, 2], 'test']; - generateTestVariants(`should pass the matchCallback return value to handlerCallback as params`, matchCallbackReturnValues, async function(returnValue) { - const handlerCallbackStub = sinon.stub().resolves(new Response()); - const router = new Router(); - const route = new Route( + generateTestVariants( + `should pass the matchCallback return value to handlerCallback as params`, + matchCallbackReturnValues, + async function (returnValue) { + const handlerCallbackStub = sinon.stub().resolves(new Response()); + const router = new Router(); + const route = new Route( sinon.stub().returns(returnValue), handlerCallbackStub, - ); - router.registerRoute(route); + ); + router.registerRoute(route); - const request = new Request(location); - const event = new FetchEvent('fetch', {request}); - await router.handleRequest({request, event}); + const request = new Request(location); + const event = new FetchEvent('fetch', {request}); + await router.handleRequest({request, event}); - expect(handlerCallbackStub.calledOnce).to.be.true; - expect(handlerCallbackStub.firstCall.args[0].params).to.eql(returnValue); - }); + expect(handlerCallbackStub.calledOnce).to.be.true; + expect(handlerCallbackStub.firstCall.args[0].params).to.eql( + returnValue, + ); + }, + ); - it(`should not throw for router with no-routes set`, async function() { + it(`should not throw for router with no-routes set`, async function () { const router = new Router(); const request = new Request(location); @@ -655,13 +788,10 @@ describe(`Router`, function() { await router.handleRequest({request, event}); }); - it(`should set the matchCallback's sameOrigin to false when called with a cross-origin request`, async function() { + it(`should set the matchCallback's sameOrigin to false when called with a cross-origin request`, async function () { const router = new Router(); const matchCallbackStub = sandbox.stub(); - const route = new Route( - matchCallbackStub, - () => new Response(), - ); + const route = new Route(matchCallbackStub, () => new Response()); router.registerRoute(route); const request = new Request('https://cross-origin.example.com'); @@ -671,13 +801,10 @@ describe(`Router`, function() { expect(matchCallbackStub.args[0][0].sameOrigin).to.be.false; }); - it(`should set the matchCallback's sameOrigin to true when called with a same-origin request`, async function() { + it(`should set the matchCallback's sameOrigin to true when called with a same-origin request`, async function () { const router = new Router(); const matchCallbackStub = sandbox.stub(); - const route = new Route( - matchCallbackStub, - () => new Response(), - ); + const route = new Route(matchCallbackStub, () => new Response()); router.registerRoute(route); const request = new Request(location.href); @@ -688,14 +815,17 @@ describe(`Router`, function() { }); }); - describe(`findMatchingRoute()`, function() { - it(`should log a warning in development when an async matchCallback is used`, function() { + describe(`findMatchingRoute()`, function () { + it(`should log a warning in development when an async matchCallback is used`, function () { if (process.env.NODE_ENV === 'production') return this.skip(); const loggerStub = sandbox.stub(logger, 'warn'); const router = new Router(); - const route = new Route(async () => true, () => new Response()); + const route = new Route( + async () => true, + () => new Response(), + ); router.registerRoute(route); const url = new URL(location.href); @@ -710,7 +840,7 @@ describe(`Router`, function() { expect(loggerStub.firstCall.args[0]).to.include('async'); }); - it(`should return the first matching route`, function() { + it(`should return the first matching route`, function () { const router = new Router(); const match1 = sandbox.stub().returns(false); @@ -730,7 +860,12 @@ describe(`Router`, function() { const event = new FetchEvent('fetch', {request}); const sameOrigin = true; - const {route} = router.findMatchingRoute({url, sameOrigin, request, event}); + const {route} = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(match1.callCount).to.equal(1); expect(match2.callCount).to.equal(1); @@ -739,7 +874,7 @@ describe(`Router`, function() { expect(route).to.equal(route2); }); - it(`should invoke route match functions with the correct arguments`, function() { + it(`should invoke route match functions with the correct arguments`, function () { const router = new Router(); const match1 = sandbox.stub().returns(false); @@ -755,7 +890,12 @@ describe(`Router`, function() { const event = new FetchEvent('fetch', {request}); const sameOrigin = true; - const {route} = router.findMatchingRoute({url, sameOrigin, request, event}); + const {route} = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(match1.callCount).to.equal(1); expect(match1.args[0][0]).to.eql({url, sameOrigin, request, event}); @@ -766,15 +906,22 @@ describe(`Router`, function() { expect(route).to.equal(route2); }); - it(`should return the route and params (if applicable)`, function() { + it(`should return the route and params (if applicable)`, function () { const router = new Router(); - const match = sandbox.stub() - .onCall(0).returns(true) - .onCall(1).returns('truthy') - .onCall(2).returns([1, 2, 3]) - .onCall(3).returns([]) - .onCall(4).returns({a: 1}) - .onCall(5).returns({}); + const match = sandbox + .stub() + .onCall(0) + .returns(true) + .onCall(1) + .returns('truthy') + .onCall(2) + .returns([1, 2, 3]) + .onCall(3) + .returns([]) + .onCall(4) + .returns({a: 1}) + .onCall(5) + .returns({}); const route = new Route(match, () => new Response()); router.registerRoute(route); @@ -784,27 +931,57 @@ describe(`Router`, function() { const event = new FetchEvent('fetch', {request}); const sameOrigin = true; - const result1 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result1 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result1.route).to.equal(route); expect(result1.params).to.equal(undefined); - const result2 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result2 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result2.route).to.equal(route); expect(result2.params).to.equal('truthy'); - const result3 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result3 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result3.route).to.equal(route); expect(result3.params).to.deep.equal([1, 2, 3]); - const result4 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result4 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result4.route).to.equal(route); expect(result4.params).to.equal(undefined); - const result5 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result5 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result5.route).to.equal(route); expect(result5.params).to.deep.equal({a: 1}); - const result6 = router.findMatchingRoute({url, sameOrigin, request, event}); + const result6 = router.findMatchingRoute({ + url, + sameOrigin, + request, + event, + }); expect(result6.route).to.equal(route); expect(result6.params).to.equal(undefined); }); diff --git a/test/workbox-routing/sw/test-registerRoute.mjs b/test/workbox-routing/sw/test-registerRoute.mjs index 793f2d377..037c37a91 100644 --- a/test/workbox-routing/sw/test-registerRoute.mjs +++ b/test/workbox-routing/sw/test-registerRoute.mjs @@ -12,12 +12,11 @@ import {RegExpRoute} from 'workbox-routing/RegExpRoute.mjs'; import {registerRoute} from 'workbox-routing/registerRoute.mjs'; import {Route} from 'workbox-routing/Route.mjs'; - -describe(`registerRoute()`, function() { +describe(`registerRoute()`, function () { const sandbox = sinon.createSandbox(); let defaultRouter; - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); if (logger) { @@ -33,7 +32,7 @@ describe(`registerRoute()`, function() { sandbox.spy(defaultRouter, 'registerRoute'); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } @@ -46,30 +45,37 @@ describe(`registerRoute()`, function() { // This is needed because we're skipping the last test, which for some // reasons seems to be skipping the afterEach hook: // https://github.com/mochajs/mocha/pull/2571#issuecomment-477407091 - after(function() { + after(function () { sandbox.restore(); }); - it(`should use the default router instance`, function() { + it(`should use the default router instance`, function () { expect(defaultRouter.registerRoute.callCount).to.equal(0); registerRoute('/abc', sandbox.spy()); expect(defaultRouter.registerRoute.callCount).to.equal(1); }); - it(`should throw when using a string that doesn't start with '/' or 'http' is used.`, async function() { + it(`should throw when using a string that doesn't start with '/' or 'http' is used.`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); await expectError( - () => registerRoute('invalid-start', sandbox.stub()), - 'invalid-string', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('funcName').that.equals('registerRoute'); - expect(error.details).to.have.property('paramName').that.equals('capture'); - }); + () => registerRoute('invalid-start', sandbox.stub()), + 'invalid-string', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('funcName') + .that.equals('registerRoute'); + expect(error.details) + .to.have.property('paramName') + .that.equals('capture'); + }, + ); }); - it(`should handle a string for input and return a route that can be unregistered.`, async function() { + it(`should handle a string for input and return a route that can be unregistered.`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const handlerSpy = sandbox.spy(); @@ -94,7 +100,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should handle a string for input, matching same-origin requests, and return a route that can be unregistered.`, async function() { + it(`should handle a string for input, matching same-origin requests, and return a route that can be unregistered.`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const handlerSpy = sandbox.spy(); @@ -106,8 +112,9 @@ describe(`registerRoute()`, function() { const sameOriginURL = new URL(pathname, location); const sameOriginRequest = new Request(sameOriginURL); - const sameOriginEvent = - new FetchEvent('fetch', {request: sameOriginRequest}); + const sameOriginEvent = new FetchEvent('fetch', { + request: sameOriginRequest, + }); await defaultRouter.handleRequest({ request: sameOriginRequest, @@ -115,10 +122,10 @@ describe(`registerRoute()`, function() { }); const sameOriginURLNotMatching = new URL('/does/not/match', location); - const sameOriginRequestNotMatching = - new Request(sameOriginURLNotMatching); - const sameOriginEventNotMatching = - new FetchEvent('fetch', {request: sameOriginRequestNotMatching}); + const sameOriginRequestNotMatching = new Request(sameOriginURLNotMatching); + const sameOriginEventNotMatching = new FetchEvent('fetch', { + request: sameOriginRequestNotMatching, + }); await defaultRouter.handleRequest({ request: sameOriginRequestNotMatching, @@ -127,8 +134,9 @@ describe(`registerRoute()`, function() { const crossOriginURL = new URL(pathname, crossOrigin); const crossOriginRequest = new Request(crossOriginURL); - const crossOriginEvent = - new FetchEvent('fetch', {request: crossOriginRequest}); + const crossOriginEvent = new FetchEvent('fetch', { + request: crossOriginRequest, + }); await defaultRouter.handleRequest({ request: crossOriginRequest, @@ -150,7 +158,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should handle a string for input, matching cross-origin requests, and return a route that can be unregistered.`, async function() { + it(`should handle a string for input, matching cross-origin requests, and return a route that can be unregistered.`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const handlerSpy = sandbox.spy(); @@ -162,8 +170,9 @@ describe(`registerRoute()`, function() { const sameOriginURL = new URL(pathname, location); const sameOriginRequest = new Request(sameOriginURL); - const sameOriginEvent = - new FetchEvent('fetch', {request: sameOriginRequest}); + const sameOriginEvent = new FetchEvent('fetch', { + request: sameOriginRequest, + }); await defaultRouter.handleRequest({ request: sameOriginRequest, @@ -172,8 +181,9 @@ describe(`registerRoute()`, function() { const crossOriginURL = new URL(pathname, crossOrigin); const crossOriginRequest = new Request(crossOriginURL); - const crossOriginEvent = - new FetchEvent('fetch', {request: crossOriginRequest}); + const crossOriginEvent = new FetchEvent('fetch', { + request: crossOriginRequest, + }); await defaultRouter.handleRequest({ request: crossOriginRequest, @@ -194,7 +204,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should handle a regex for input and return a route that can be unregistered.`, async function() { + it(`should handle a regex for input and return a route that can be unregistered.`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const handlerSpy = sandbox.spy(); @@ -218,7 +228,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should handle a function for input and return a route that can be unregistered.`, async function() { + it(`should handle a function for input and return a route that can be unregistered.`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const captureSpy = sandbox.stub().returns(true); const handlerSpy = sandbox.spy(); @@ -246,13 +256,13 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should throw on unexpected capture`, function() { + it(`should throw on unexpected capture`, function () { return expectError(() => { registerRoute([], () => {}); }, 'unsupported-route-type'); }); - it(`should allow registering a normal Route`, async function() { + it(`should allow registering a normal Route`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const captureSpy = sandbox.stub().callsFake(() => true); const handlerSpy = sandbox.spy(); @@ -281,7 +291,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should allow registering a class that extends Route`, async function() { + it(`should allow registering a class that extends Route`, async function () { const defaultRouter = getOrCreateDefaultRouter(); const handlerSpy = sandbox.spy(); @@ -306,7 +316,7 @@ describe(`registerRoute()`, function() { expect(handlerSpy.callCount).to.equal(0); }); - it(`should log for express styles routes`, function() { + it(`should log for express styles routes`, function () { if (process.env.NODE_ENV === 'production') this.skip(); registerRoute('/:example/', () => {}); diff --git a/test/workbox-routing/sw/test-setCatchHandler.mjs b/test/workbox-routing/sw/test-setCatchHandler.mjs index 5b9bfdcda..582bbb6f5 100644 --- a/test/workbox-routing/sw/test-setCatchHandler.mjs +++ b/test/workbox-routing/sw/test-setCatchHandler.mjs @@ -9,11 +9,11 @@ import {setCatchHandler} from 'workbox-routing/setCatchHandler.mjs'; import {getOrCreateDefaultRouter} from 'workbox-routing/utils/getOrCreateDefaultRouter.mjs'; -describe(`setCatchHandler()`, function() { +describe(`setCatchHandler()`, function () { const sandbox = sinon.createSandbox(); let defaultRouter; - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); // Spy on all added event listeners so they can be removed. @@ -22,14 +22,14 @@ describe(`setCatchHandler()`, function() { defaultRouter = getOrCreateDefaultRouter(); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should call setCatchHandler() on the default router`, function() { + it(`should call setCatchHandler() on the default router`, function () { sandbox.stub(defaultRouter, 'setCatchHandler'); const handler = sandbox.spy(); diff --git a/test/workbox-routing/sw/test-setDefaultHandler.mjs b/test/workbox-routing/sw/test-setDefaultHandler.mjs index ab833e9ab..5a479a8eb 100644 --- a/test/workbox-routing/sw/test-setDefaultHandler.mjs +++ b/test/workbox-routing/sw/test-setDefaultHandler.mjs @@ -9,11 +9,11 @@ import {setDefaultHandler} from 'workbox-routing/setDefaultHandler.mjs'; import {getOrCreateDefaultRouter} from 'workbox-routing/utils/getOrCreateDefaultRouter.mjs'; -describe(`setDefaultHandler()`, function() { +describe(`setDefaultHandler()`, function () { const sandbox = sinon.createSandbox(); let defaultRouter; - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); // Spy on all added event listeners so they can be removed. @@ -22,14 +22,14 @@ describe(`setDefaultHandler()`, function() { defaultRouter = getOrCreateDefaultRouter(); }); - afterEach(function() { + afterEach(function () { for (const args of self.addEventListener.args) { self.removeEventListener(...args); } sandbox.restore(); }); - it(`should call setDefaultHandler() on the default router`, function() { + it(`should call setDefaultHandler() on the default router`, function () { sandbox.stub(defaultRouter, 'setDefaultHandler'); const handler = sandbox.spy(); diff --git a/test/workbox-routing/sw/utils/test-normalizeHandler.mjs b/test/workbox-routing/sw/utils/test-normalizeHandler.mjs index 44a2ab917..8b8cad2d7 100644 --- a/test/workbox-routing/sw/utils/test-normalizeHandler.mjs +++ b/test/workbox-routing/sw/utils/test-normalizeHandler.mjs @@ -8,7 +8,6 @@ import {normalizeHandler} from 'workbox-routing/utils/normalizeHandler.mjs'; - const handler = { handle: () => {}, }; @@ -17,59 +16,75 @@ const functionHandler = () => {}; const invalidHandlerObject = {}; const invalidHandlerString = 'INVALID'; -describe(`normalizeHandler()`, function() { - it(`should properly normalize an object that exposes a handle method in dev`, async function() { +describe(`normalizeHandler()`, function () { + it(`should properly normalize an object that exposes a handle method in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); const normalizedHandler = normalizeHandler(handler); expect(normalizedHandler).to.have.property('handle'); }); - it(`should properly normalize a function in dev`, async function() { + it(`should properly normalize a function in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); const normalizedHandler = normalizeHandler(functionHandler); expect(normalizedHandler).to.have.property('handle'); }); - it(`should throw when called with an object that doesn't expose a handle method in dev`, async function() { + it(`should throw when called with an object that doesn't expose a handle method in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); await expectError( - () => normalizeHandler(invalidHandlerObject), - 'missing-a-method', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => normalizeHandler(invalidHandlerObject), + 'missing-a-method', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); }); - it(`should throw when called with something other than a function or an object in dev`, async function() { + it(`should throw when called with something other than a function or an object in dev`, async function () { if (process.env.NODE_ENV === 'production') return this.skip(); await expectError( - () => normalizeHandler(invalidHandlerString), - 'incorrect-type', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-routing'); - expect(error.details).to.have.property('className').that.equals('Route'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('handler'); - }, + () => normalizeHandler(invalidHandlerString), + 'incorrect-type', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-routing'); + expect(error.details) + .to.have.property('className') + .that.equals('Route'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('handler'); + }, ); }); - it(`should properly normalize an object that exposes a handle method in production`, async function() { + it(`should properly normalize an object that exposes a handle method in production`, async function () { if (process.env.NODE_ENV !== 'production') return this.skip(); const normalizedHandler = normalizeHandler(handler); expect(normalizedHandler).to.have.property('handle'); }); - it(`should properly normalize a function in production`, async function() { + it(`should properly normalize a function in production`, async function () { if (process.env.NODE_ENV !== 'production') return this.skip(); const normalizedHandler = normalizeHandler(functionHandler); diff --git a/test/workbox-strategies/integration/test-cacheFirst.js b/test/workbox-strategies/integration/test-cacheFirst.js index a1f5bed80..a90cd63e4 100644 --- a/test/workbox-strategies/integration/test-cacheFirst.js +++ b/test/workbox-strategies/integration/test-cacheFirst.js @@ -11,44 +11,62 @@ const expect = require('chai').expect; const activateAndControlSW = require('../../../infra/testing/activate-and-control'); const cleanSWEnv = require('../../../infra/testing/clean-sw'); -describe(`[workbox-strategies] CacheFirst Requests`, function() { +describe(`[workbox-strategies] CacheFirst Requests`, function () { const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-strategies/static/cache-first/`; let requestCounter; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`); requestCounter = global.__workbox.server.startCountingRequests(); }); - afterEach(function() { + afterEach(function () { global.__workbox.server.stopCountingRequests(requestCounter); }); - it(`should respond with a cached response`, async function() { + it(`should respond with a cached response`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. await activateAndControlSW(swURL); let response = await global.__workbox.webdriver.executeAsyncScript((cb) => { - fetch(new URL(`/test/workbox-strategies/static/cache-first/example.txt`, location).href) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + fetch( + new URL( + `/test/workbox-strategies/static/cache-first/example.txt`, + location, + ).href, + ) + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); expect(response.trim()).to.equal('hello'); - expect(requestCounter.getURLCount('/test/workbox-strategies/static/cache-first/example.txt')).to.eql(1); + expect( + requestCounter.getURLCount( + '/test/workbox-strategies/static/cache-first/example.txt', + ), + ).to.eql(1); // This request should come from cache and not the server response = await global.__workbox.webdriver.executeAsyncScript((cb) => { - fetch(new URL(`/test/workbox-strategies/static/cache-first/example.txt`, location).href) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + fetch( + new URL( + `/test/workbox-strategies/static/cache-first/example.txt`, + location, + ).href, + ) + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); expect(response.trim()).to.equal('hello'); - expect(requestCounter.getURLCount('/test/workbox-strategies/static/cache-first/example.txt')).to.eql(1); + expect( + requestCounter.getURLCount( + '/test/workbox-strategies/static/cache-first/example.txt', + ), + ).to.eql(1); }); }); diff --git a/test/workbox-strategies/integration/test-cacheOnly.js b/test/workbox-strategies/integration/test-cacheOnly.js index a7190ad79..2fccc01fe 100644 --- a/test/workbox-strategies/integration/test-cacheOnly.js +++ b/test/workbox-strategies/integration/test-cacheOnly.js @@ -11,15 +11,15 @@ const expect = require('chai').expect; const activateAndControlSW = require('../../../infra/testing/activate-and-control'); const cleanSWEnv = require('../../../infra/testing/clean-sw'); -describe(`[workbox-strategies] CacheOnly`, function() { +describe(`[workbox-strategies] CacheOnly`, function () { const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-strategies/static/cache-only/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`); }); - it(`should respond with a cached response`, async function() { + it(`should respond with a cached response`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. @@ -27,17 +27,17 @@ describe(`[workbox-strategies] CacheOnly`, function() { let response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/CacheOnly/InCache/`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); expect(response).to.eql('Cached'); response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/CacheOnly/NotInCache/`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); expect(response).to.not.eql('Cached'); }); diff --git a/test/workbox-strategies/integration/test-networkFirst.js b/test/workbox-strategies/integration/test-networkFirst.js index c04b88925..28e5061a6 100644 --- a/test/workbox-strategies/integration/test-networkFirst.js +++ b/test/workbox-strategies/integration/test-networkFirst.js @@ -13,15 +13,15 @@ const cleanSWEnv = require('../../../infra/testing/clean-sw'); const runInSW = require('../../../infra/testing/comlink/node-interface'); const waitUntil = require('../../../infra/testing/wait-until'); -describe(`[workbox-strategies] NetworkFirst Requests`, function() { +describe(`[workbox-strategies] NetworkFirst Requests`, function () { const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-strategies/static/network-first/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`); }); - it(`should respond with a non-cached entry but stash request in a cache`, async function() { + it(`should respond with a non-cached entry but stash request in a cache`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. @@ -31,31 +31,39 @@ describe(`[workbox-strategies] NetworkFirst Requests`, function() { let response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const firstResponse = response.trim(); expect(firstResponse).to.not.equal('Cached'); // Writing to the cache is asynchronous, so this might not happen right away. await waitUntil(async () => { - const responseText = await runInSW('getCachedResponseText', cacheName, '/__WORKBOX/uniqueValue'); + const responseText = await runInSW( + 'getCachedResponseText', + cacheName, + '/__WORKBOX/uniqueValue', + ); return responseText === firstResponse; }); response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const secondResponse = response.trim(); expect(secondResponse).to.not.equal(firstResponse); // Writing to the cache is asynchronous, so this might not happen right away. await waitUntil(async () => { - const responseText = await runInSW('getCachedResponseText', cacheName, '/__WORKBOX/uniqueValue'); + const responseText = await runInSW( + 'getCachedResponseText', + cacheName, + '/__WORKBOX/uniqueValue', + ); return responseText === secondResponse; }); }); diff --git a/test/workbox-strategies/integration/test-networkOnly.js b/test/workbox-strategies/integration/test-networkOnly.js index be01549f5..deefd5435 100644 --- a/test/workbox-strategies/integration/test-networkOnly.js +++ b/test/workbox-strategies/integration/test-networkOnly.js @@ -12,15 +12,15 @@ const activateAndControlSW = require('../../../infra/testing/activate-and-contro const cleanSWEnv = require('../../../infra/testing/clean-sw'); const runInSW = require('../../../infra/testing/comlink/node-interface'); -describe(`[workbox-strategies] NetworkOnly Requests`, function() { +describe(`[workbox-strategies] NetworkOnly Requests`, function () { const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-strategies/static/network-only/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`); }); - it(`should respond with a non-cached entry`, async function() { + it(`should respond with a non-cached entry`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. @@ -28,9 +28,9 @@ describe(`[workbox-strategies] NetworkOnly Requests`, function() { let response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const firstResponse = response.trim(); expect(firstResponse).to.not.eql('Cached'); @@ -39,9 +39,9 @@ describe(`[workbox-strategies] NetworkOnly Requests`, function() { response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const secondResponse = response.trim(); expect(secondResponse).to.not.eql(firstResponse); diff --git a/test/workbox-strategies/integration/test-staleWhileRevalidate.js b/test/workbox-strategies/integration/test-staleWhileRevalidate.js index dce2c972e..3f9f99156 100644 --- a/test/workbox-strategies/integration/test-staleWhileRevalidate.js +++ b/test/workbox-strategies/integration/test-staleWhileRevalidate.js @@ -13,15 +13,15 @@ const cleanSWEnv = require('../../../infra/testing/clean-sw'); const runInSW = require('../../../infra/testing/comlink/node-interface'); const waitUntil = require('../../../infra/testing/wait-until'); -describe(`[workbox-strategies] StaleWhileRevalidate Requests`, function() { +describe(`[workbox-strategies] StaleWhileRevalidate Requests`, function () { const baseURL = `${global.__workbox.server.getAddress()}/test/workbox-strategies/static/stale-while-revalidate/`; - beforeEach(async function() { + beforeEach(async function () { // Navigate to our test page and clear all caches before this test runs. await cleanSWEnv(global.__workbox.webdriver, `${baseURL}integration.html`); }); - it(`should respond with cached entry and update it`, async function() { + it(`should respond with cached entry and update it`, async function () { const swURL = `${baseURL}sw.js`; // Wait for the service worker to register and activate. @@ -31,24 +31,28 @@ describe(`[workbox-strategies] StaleWhileRevalidate Requests`, function() { let response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const firstResponse = response.trim(); // Writing to the cache is asynchronous, so this might not happen right away. await waitUntil(async () => { - const responseText = await runInSW('getCachedResponseText', cacheName, '/__WORKBOX/uniqueValue'); + const responseText = await runInSW( + 'getCachedResponseText', + cacheName, + '/__WORKBOX/uniqueValue', + ); return responseText === firstResponse; }); // This response should come from cache and not the server response = await global.__workbox.webdriver.executeAsyncScript((cb) => { fetch(`/__WORKBOX/uniqueValue`) - .then((response) => response.text()) - .then((responseBody) => cb(responseBody)) - .catch((err) => cb(err.message)); + .then((response) => response.text()) + .then((responseBody) => cb(responseBody)) + .catch((err) => cb(err.message)); }); const secondResponse = response.trim(); expect(secondResponse).to.eql(firstResponse); @@ -56,7 +60,11 @@ describe(`[workbox-strategies] StaleWhileRevalidate Requests`, function() { // Writing to the cache is asynchronous, so this might not happen right away. // We expect a new value, updated from the network, different than secondResponse. await waitUntil(async () => { - const responseText = await runInSW('getCachedResponseText', cacheName, '/__WORKBOX/uniqueValue'); + const responseText = await runInSW( + 'getCachedResponseText', + cacheName, + '/__WORKBOX/uniqueValue', + ); return responseText !== secondResponse; }); }); diff --git a/test/workbox-strategies/integration/test-sw.js b/test/workbox-strategies/integration/test-sw.js index 5d6e07135..5eb808003 100644 --- a/test/workbox-strategies/integration/test-sw.js +++ b/test/workbox-strategies/integration/test-sw.js @@ -8,9 +8,8 @@ const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - -describe(`[workbox-strategies]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-strategies]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-strategies/sw/'); }); }); diff --git a/test/workbox-strategies/static/cache-first/sw.js b/test/workbox-strategies/static/cache-first/sw.js index fc6da7c77..552a32d0b 100644 --- a/test/workbox-strategies/static/cache-first/sw.js +++ b/test/workbox-strategies/static/cache-first/sw.js @@ -12,9 +12,13 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); workbox.routing.registerRoute( - new RegExp('/test/workbox-strategies/static/cache-first/example.txt'), - new workbox.strategies.CacheFirst(), + new RegExp('/test/workbox-strategies/static/cache-first/example.txt'), + new workbox.strategies.CacheFirst(), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-strategies/static/cache-only/sw.js b/test/workbox-strategies/static/cache-only/sw.js index 99e11016c..f48fc98a3 100644 --- a/test/workbox-strategies/static/cache-only/sw.js +++ b/test/workbox-strategies/static/cache-only/sw.js @@ -12,13 +12,18 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); workbox.routing.registerRoute( - new RegExp('/CacheOnly/.*/'), - new workbox.strategies.CacheOnly(), + new RegExp('/CacheOnly/.*/'), + new workbox.strategies.CacheOnly(), ); -self.addEventListener('install', (event) => event.waitUntil( - caches.open(workbox.core.cacheNames.runtime) - .then((cache) => cache.put('/CacheOnly/InCache/', new Response('Cached'))) - .then(() => self.skipWaiting())), +self.addEventListener('install', (event) => + event.waitUntil( + caches + .open(workbox.core.cacheNames.runtime) + .then((cache) => cache.put('/CacheOnly/InCache/', new Response('Cached'))) + .then(() => self.skipWaiting()), + ), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), ); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); diff --git a/test/workbox-strategies/static/network-first/sw.js b/test/workbox-strategies/static/network-first/sw.js index 84cf6a2b4..0a067dacc 100644 --- a/test/workbox-strategies/static/network-first/sw.js +++ b/test/workbox-strategies/static/network-first/sw.js @@ -12,17 +12,22 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); workbox.routing.registerRoute( - new RegExp('/__WORKBOX/uniqueValue'), - new workbox.strategies.NetworkFirst({ - cacheName: 'network-first', - }), + new RegExp('/__WORKBOX/uniqueValue'), + new workbox.strategies.NetworkFirst({ + cacheName: 'network-first', + }), ); self.addEventListener('install', (event) => { self.skipWaiting(); event.waitUntil( - caches.open('network-first') - .then((cache) => cache.put('/__WORKBOX/uniqueValue', new Response('Cached'))), + caches + .open('network-first') + .then((cache) => + cache.put('/__WORKBOX/uniqueValue', new Response('Cached')), + ), ); }); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-strategies/static/network-only/sw.js b/test/workbox-strategies/static/network-only/sw.js index ef10a4027..768292f7b 100644 --- a/test/workbox-strategies/static/network-only/sw.js +++ b/test/workbox-strategies/static/network-only/sw.js @@ -12,15 +12,22 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); workbox.routing.registerRoute( - new RegExp('/__WORKBOX/uniqueValue'), - new workbox.strategies.NetworkOnly({ - cacheName: 'network-only', - }), + new RegExp('/__WORKBOX/uniqueValue'), + new workbox.strategies.NetworkOnly({ + cacheName: 'network-only', + }), ); -self.addEventListener('install', (event) => event.waitUntil( - caches.open('network-only') - .then((cache) => cache.put('/__WORKBOX/uniqueValue', new Response('Cached'))) - .then(() => self.skipWaiting())), +self.addEventListener('install', (event) => + event.waitUntil( + caches + .open('network-only') + .then((cache) => + cache.put('/__WORKBOX/uniqueValue', new Response('Cached')), + ) + .then(() => self.skipWaiting()), + ), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), ); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); diff --git a/test/workbox-strategies/static/stale-while-revalidate/sw.js b/test/workbox-strategies/static/stale-while-revalidate/sw.js index ae0e7eaf8..82c174bdc 100644 --- a/test/workbox-strategies/static/stale-while-revalidate/sw.js +++ b/test/workbox-strategies/static/stale-while-revalidate/sw.js @@ -12,11 +12,15 @@ importScripts('/infra/testing/comlink/sw-interface.js'); workbox.setConfig({modulePathPrefix: '/__WORKBOX/buildFile/'}); workbox.routing.registerRoute( - new RegExp('/__WORKBOX/uniqueValue'), - new workbox.strategies.StaleWhileRevalidate({ - cacheName: 'stale-while-revalidate', - }), + new RegExp('/__WORKBOX/uniqueValue'), + new workbox.strategies.StaleWhileRevalidate({ + cacheName: 'stale-while-revalidate', + }), ); -self.addEventListener('install', (event) => event.waitUntil(self.skipWaiting())); -self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim())); +self.addEventListener('install', (event) => + event.waitUntil(self.skipWaiting()), +); +self.addEventListener('activate', (event) => + event.waitUntil(self.clients.claim()), +); diff --git a/test/workbox-strategies/sw/plugins/test-cacheOkAndOpaquePlugin.mjs b/test/workbox-strategies/sw/plugins/test-cacheOkAndOpaquePlugin.mjs index 316957545..0d1791867 100644 --- a/test/workbox-strategies/sw/plugins/test-cacheOkAndOpaquePlugin.mjs +++ b/test/workbox-strategies/sw/plugins/test-cacheOkAndOpaquePlugin.mjs @@ -10,22 +10,27 @@ import {cacheOkAndOpaquePlugin} from 'workbox-strategies/plugins/cacheOkAndOpaqu import {generateOpaqueResponse} from '../../../../infra/testing/helpers/generateOpaqueResponse.mjs'; import {generateUniqueResponse} from '../../../../infra/testing/helpers/generateUniqueResponse.mjs'; - -describe(`cacheOkAndOpaquePlugin`, function() { +describe(`cacheOkAndOpaquePlugin`, function () { for (const status of [206, 404]) { - it(`should return null when status is ${status}`, async function() { + it(`should return null when status is ${status}`, async function () { const response = generateUniqueResponse({status}); - expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal(null); + expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal( + null, + ); }); } - it(`should return Response if status is opaque`, async function() { + it(`should return Response if status is opaque`, async function () { const response = await generateOpaqueResponse(); - expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal(response); + expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal( + response, + ); }); - it(`should return Response if status is 200`, async function() { + it(`should return Response if status is 200`, async function () { const response = generateUniqueResponse(); - expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal(response); + expect(await cacheOkAndOpaquePlugin.cacheWillUpdate({response})).to.equal( + response, + ); }); }); diff --git a/test/workbox-strategies/sw/test-CacheFirst.mjs b/test/workbox-strategies/sw/test-CacheFirst.mjs index 8431c75ed..7a4e9ab49 100644 --- a/test/workbox-strategies/sw/test-CacheFirst.mjs +++ b/test/workbox-strategies/sw/test-CacheFirst.mjs @@ -9,28 +9,30 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.mjs'; import {CacheFirst} from 'workbox-strategies/CacheFirst.mjs'; import {compareResponses} from '../../../infra/testing/helpers/compareResponses.mjs'; -import {eventDoneWaiting, spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; +import { + eventDoneWaiting, + spyOnEvent, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import {generateOpaqueResponse} from '../../../infra/testing/helpers/generateOpaqueResponse.mjs'; import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; - -describe(`CacheFirst`, function() { +describe(`CacheFirst`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`should be able to fetch and cache a request to default cache`, async function() { + describe(`handle()`, function () { + it(`should be able to fetch and cache a request to default cache`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -67,7 +69,7 @@ describe(`CacheFirst`, function() { expect(fetch.callCount).to.equal(0); }); - it(`should support using a string as the request`, async function() { + it(`should support using a string as the request`, async function () { const stringRequest = 'http://example.io/test/'; const request = new Request(stringRequest); const event = new FetchEvent('fetch', {request}); @@ -105,7 +107,7 @@ describe(`CacheFirst`, function() { expect(fetch.callCount).to.equal(0); }); - it(`should be able to cache a non-existent request to custom cache`, async function() { + it(`should be able to cache a non-existent request to custom cache`, async function () { const cacheName = 'test-cache-name'; const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); @@ -131,7 +133,7 @@ describe(`CacheFirst`, function() { await compareResponses(firstHandleResponse, firstCachedResponse, true); }); - it(`should not cache an opaque response by default`, async function() { + it(`should not cache an opaque response by default`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -155,7 +157,7 @@ describe(`CacheFirst`, function() { expect(firstHandleResponse).to.exist; }); - it(`should cache an opaque response when a cacheWillUpdate plugin returns true`, async function() { + it(`should cache an opaque response when a cacheWillUpdate plugin returns true`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -186,7 +188,7 @@ describe(`CacheFirst`, function() { await compareResponses(firstHandleResponse, firstCachedResponse, true); }); - it(`should return the plugin cache response`, async function() { + it(`should return the plugin cache response`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -216,7 +218,7 @@ describe(`CacheFirst`, function() { await compareResponses(firstHandleResponse, pluginResponse, true); }); - it(`should fallback to fetch if the plugin.cacheResponseWillBeUsed returns null`, async function() { + it(`should fallback to fetch if the plugin.cacheResponseWillBeUsed returns null`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -253,7 +255,7 @@ describe(`CacheFirst`, function() { await compareResponses(firstHandleResponse, fetchResponse, true); }); - it(`should be able to handle a network error`, async function() { + it(`should be able to handle a network error`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -263,21 +265,25 @@ describe(`CacheFirst`, function() { const cacheFirst = new CacheFirst(); await expectError( - () => cacheFirst.handle({ + () => + cacheFirst.handle({ request, event, }), - 'no-response'); + 'no-response', + ); // Wait until cache.put is finished. await eventDoneWaiting(event); }); - it(`should use the fetchOptions provided`, async function() { + it(`should use the fetchOptions provided`, async function () { const fetchOptions = {credentials: 'include'}; const cacheFirst = new CacheFirst({fetchOptions}); - const fetchStub = sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); + const fetchStub = sandbox + .stub(self, 'fetch') + .resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -294,9 +300,10 @@ describe(`CacheFirst`, function() { expect(fetchStub.calledWith(request, fetchOptions)).to.be.true; }); - it(`should use the CacheQueryOptions when performing a cache match`, async function() { - const matchStub = sandbox.stub(self.caches.constructor.prototype, 'match') - .resolves(generateUniqueResponse()); + it(`should use the CacheQueryOptions when performing a cache match`, async function () { + const matchStub = sandbox + .stub(self.caches.constructor.prototype, 'match') + .resolves(generateUniqueResponse()); const matchOptions = {ignoreSearch: true}; const cacheFirst = new CacheFirst({matchOptions}); diff --git a/test/workbox-strategies/sw/test-CacheOnly.mjs b/test/workbox-strategies/sw/test-CacheOnly.mjs index f694fe4f2..6d659afd4 100644 --- a/test/workbox-strategies/sw/test-CacheOnly.mjs +++ b/test/workbox-strategies/sw/test-CacheOnly.mjs @@ -12,39 +12,39 @@ import {compareResponses} from '../../../infra/testing/helpers/compareResponses. import {spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; - -describe(`CacheOnly`, function() { +describe(`CacheOnly`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`should not return a response when the cache isn't populated`, async function() { + describe(`handle()`, function () { + it(`should not return a response when the cache isn't populated`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); const cacheOnly = new CacheOnly(); await expectError( - () => cacheOnly.handle({ + () => + cacheOnly.handle({ request, event, }), - 'no-response', + 'no-response', ); }); - it(`should return the cached response when the cache is populated`, async function() { + it(`should return the cached response when the cache is populated`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -61,7 +61,7 @@ describe(`CacheOnly`, function() { await compareResponses(injectedResponse, handleResponse, true); }); - it(`should support using a string as the request`, async function() { + it(`should support using a string as the request`, async function () { const stringRequest = 'http://example.io/test/'; const request = new Request(stringRequest); const event = new FetchEvent('fetch', {request}); @@ -79,7 +79,7 @@ describe(`CacheOnly`, function() { await compareResponses(injectedResponse, handleResponse, true); }); - it(`should return no cached response from custom cache name`, async function() { + it(`should return no cached response from custom cache name`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -90,21 +90,24 @@ describe(`CacheOnly`, function() { const cacheOnly = new CacheOnly({cacheName: 'test-cache-name'}); await expectError( - () => cacheOnly.handle({ + () => + cacheOnly.handle({ request, event, }), - 'no-response', + 'no-response', ); }); - it(`should return cached response from custom cache name`, async function() { + it(`should return cached response from custom cache name`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); const injectedResponse = generateUniqueResponse(); - const cache = await caches.open(cacheNames.getRuntimeName('test-cache-name')); + const cache = await caches.open( + cacheNames.getRuntimeName('test-cache-name'), + ); await cache.put(request, injectedResponse.clone()); const cacheOnly = new CacheOnly({cacheName: 'test-cache-name'}); @@ -115,7 +118,7 @@ describe(`CacheOnly`, function() { await compareResponses(injectedResponse, handleResponse, true); }); - it(`should return the cached response from plugin.cachedResponseWillBeUsed`, async function() { + it(`should return the cached response from plugin.cachedResponseWillBeUsed`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -141,9 +144,10 @@ describe(`CacheOnly`, function() { await compareResponses(pluginResponse, handleResponse, true); }); - it(`should use the CacheQueryOptions when performing a cache match`, async function() { - const matchStub = sandbox.stub(self.caches.constructor.prototype, 'match') - .resolves(generateUniqueResponse()); + it(`should use the CacheQueryOptions when performing a cache match`, async function () { + const matchStub = sandbox + .stub(self.caches.constructor.prototype, 'match') + .resolves(generateUniqueResponse()); const matchOptions = {ignoreSearch: true}; const cacheOnly = new CacheOnly({matchOptions}); diff --git a/test/workbox-strategies/sw/test-NetworkFirst.mjs b/test/workbox-strategies/sw/test-NetworkFirst.mjs index 3cfd8ad53..b0de8414c 100644 --- a/test/workbox-strategies/sw/test-NetworkFirst.mjs +++ b/test/workbox-strategies/sw/test-NetworkFirst.mjs @@ -9,29 +9,31 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.mjs'; import {NetworkFirst} from 'workbox-strategies/NetworkFirst.mjs'; import {compareResponses} from '../../../infra/testing/helpers/compareResponses.mjs'; -import {eventDoneWaiting, spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; +import { + eventDoneWaiting, + spyOnEvent, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import {generateOpaqueResponse} from '../../../infra/testing/helpers/generateOpaqueResponse.mjs'; import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; import {sleep} from '../../../infra/testing/helpers/sleep.mjs'; - -describe(`NetworkFirst`, function() { +describe(`NetworkFirst`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`should add the network response to the cache`, async function() { + describe(`handle()`, function () { + it(`should add the network response to the cache`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -54,7 +56,7 @@ describe(`NetworkFirst`, function() { await compareResponses(cachedResponse, handleResponse, true); }); - it(`should support using a string as the request`, async function() { + it(`should support using a string as the request`, async function () { const stringRequest = 'http://example.io/test/'; const request = new Request(stringRequest); const event = new FetchEvent('fetch', {request}); @@ -78,7 +80,7 @@ describe(`NetworkFirst`, function() { await compareResponses(cachedResponse, handleResponse, true); }); - it(`should return the cached response if exists and not update the cache when the network request fails`, async function() { + it(`should return the cached response if exists and not update the cache when the network request fails`, async function () { sandbox.stub(self, 'fetch').rejects(new Error('Injected error.')); const request = new Request('http://example.io/test/'); @@ -91,11 +93,12 @@ describe(`NetworkFirst`, function() { const networkFirst = new NetworkFirst(); await expectError( - () => networkFirst.handle({ + () => + networkFirst.handle({ request, event: event1, }), - 'no-response', + 'no-response', ); await eventDoneWaiting(event1); @@ -118,7 +121,7 @@ describe(`NetworkFirst`, function() { await compareResponses(cachedResponse, secondCachedResponse, true); }); - it(`should return the cached response if the network request times out`, async function() { + it(`should return the cached response if the network request times out`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -127,8 +130,9 @@ describe(`NetworkFirst`, function() { // Note Sinon fake timers do not work with `await timeout()` used // in the current `StrategyHandler` implementation. const networkTimeoutSeconds = 0.5; - const sleepLongerThanNetworkTimeout = - sleep(2 * networkTimeoutSeconds * 1000); + const sleepLongerThanNetworkTimeout = sleep( + 2 * networkTimeoutSeconds * 1000, + ); sandbox.stub(self, 'fetch').callsFake(async (req) => { await sleepLongerThanNetworkTimeout; @@ -152,7 +156,7 @@ describe(`NetworkFirst`, function() { await compareResponses(populatedCacheResponse, injectedResponse, true); }); - it(`should signal completion if the network request completes before timing out`, async function() { + it(`should signal completion if the network request completes before timing out`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -177,7 +181,7 @@ describe(`NetworkFirst`, function() { await compareResponses(populatedCacheResponse, injectedResponse, true); }); - it(`should return the network response if the timeout is exceeded, but there is no cached response`, async function() { + it(`should return the network response if the timeout is exceeded, but there is no cached response`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -186,8 +190,9 @@ describe(`NetworkFirst`, function() { // Note Sinon fake timers do not work with `await timeout()` used // in the current `StrategyHandler` implementation. const networkTimeoutSeconds = 0.5; - const sleepLongerThanNetworkTimeout = - sleep(2 * networkTimeoutSeconds * 1000); + const sleepLongerThanNetworkTimeout = sleep( + 2 * networkTimeoutSeconds * 1000, + ); const networkResponse = new Response('from network'); @@ -212,19 +217,23 @@ describe(`NetworkFirst`, function() { expect(caches.match.firstCall.args[0]).to.equal(request); }); - it(`should throw when NetworkFirst() is called with an invalid networkTimeoutSeconds parameter`, function() { + it(`should throw when NetworkFirst() is called with an invalid networkTimeoutSeconds parameter`, function () { if (process.env.NODE_ENV === 'production') this.skip(); - return expectError(() => new NetworkFirst({networkTimeoutSeconds: 'invalid'}), 'incorrect-type', (err) => { - expect(err.details.paramName).to.deep.equal('networkTimeoutSeconds'); - expect(err.details.expectedType).to.deep.equal('number'); - expect(err.details.moduleName).to.deep.equal('workbox-strategies'); - expect(err.details.className).to.deep.equal('NetworkFirst'); - expect(err.details.funcName).to.deep.equal('constructor'); - }); + return expectError( + () => new NetworkFirst({networkTimeoutSeconds: 'invalid'}), + 'incorrect-type', + (err) => { + expect(err.details.paramName).to.deep.equal('networkTimeoutSeconds'); + expect(err.details.expectedType).to.deep.equal('number'); + expect(err.details.moduleName).to.deep.equal('workbox-strategies'); + expect(err.details.className).to.deep.equal('NetworkFirst'); + expect(err.details.funcName).to.deep.equal('constructor'); + }, + ); }); - it(`should return the network response and update the cache when the network request succeeds`, async function() { + it(`should return the network response and update the cache when the network request succeeds`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -252,7 +261,7 @@ describe(`NetworkFirst`, function() { await compareResponses(handleResponse, currentCachedResponse, true); }); - it(`should update the cache with an the opaque cross-origin network response`, async function() { + it(`should update the cache with an the opaque cross-origin network response`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -275,7 +284,7 @@ describe(`NetworkFirst`, function() { expect(cachedResponse.status).to.equal(0); }); - it(`should not cache an opaque response if they add a custom plugin`, async function() { + it(`should not cache an opaque response if they add a custom plugin`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -284,9 +293,7 @@ describe(`NetworkFirst`, function() { sandbox.stub(self, 'fetch').resolves(fetchResponse); const networkFirst = new NetworkFirst({ - plugins: [ - {cacheWillUpdate: () => null}, - ], + plugins: [{cacheWillUpdate: () => null}], }); const handleResponse = await networkFirst.handle({ @@ -302,11 +309,13 @@ describe(`NetworkFirst`, function() { expect(cachedResponse).to.not.exist; }); - it(`should use the fetchOptions provided`, async function() { + it(`should use the fetchOptions provided`, async function () { const fetchOptions = {credentials: 'include'}; const networkFirst = new NetworkFirst({fetchOptions}); - const fetchStub = sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); + const fetchStub = sandbox + .stub(self, 'fetch') + .resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -322,9 +331,10 @@ describe(`NetworkFirst`, function() { expect(fetchStub.calledWith(request, fetchOptions)).to.be.true; }); - it(`should use the CacheQueryOptions when performing a cache match`, async function() { - const matchStub = sandbox.stub(self.caches.constructor.prototype, 'match') - .resolves(generateUniqueResponse()); + it(`should use the CacheQueryOptions when performing a cache match`, async function () { + const matchStub = sandbox + .stub(self.caches.constructor.prototype, 'match') + .resolves(generateUniqueResponse()); sandbox.stub(self, 'fetch').callsFake(() => Promise.reject(new Error())); diff --git a/test/workbox-strategies/sw/test-NetworkOnly.mjs b/test/workbox-strategies/sw/test-NetworkOnly.mjs index 9adbd4a9b..7143f5421 100644 --- a/test/workbox-strategies/sw/test-NetworkOnly.mjs +++ b/test/workbox-strategies/sw/test-NetworkOnly.mjs @@ -12,24 +12,23 @@ import {spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils. import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; import {sleep} from '../../../infra/testing/helpers/sleep.mjs'; - -describe(`NetworkOnly`, function() { +describe(`NetworkOnly`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`should return a response without adding anything to the cache when the network request is successful`, async function() { + describe(`handle()`, function () { + it(`should return a response without adding anything to the cache when the network request is successful`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); @@ -49,7 +48,7 @@ describe(`NetworkOnly`, function() { expect(keys).to.be.empty; }); - it(`should support using a string as the request`, async function() { + it(`should support using a string as the request`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); const stringRequest = 'http://example.io/test/'; @@ -70,7 +69,7 @@ describe(`NetworkOnly`, function() { expect(keys).to.be.empty; }); - it(`should reject when the network request fails`, async function() { + it(`should reject when the network request fails`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -81,15 +80,16 @@ describe(`NetworkOnly`, function() { const networkOnly = new NetworkOnly(); await expectError( - () => networkOnly.handle({ + () => + networkOnly.handle({ request, event, }), - 'no-response', + 'no-response', ); }); - it(`should use plugins response`, async function() { + it(`should use plugins response`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -122,11 +122,13 @@ describe(`NetworkOnly`, function() { expect(keys).to.be.empty; }); - it(`should use the fetchOptions provided`, async function() { + it(`should use the fetchOptions provided`, async function () { const fetchOptions = {credentials: 'include'}; const networkOnly = new NetworkOnly({fetchOptions}); - const fetchStub = sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); + const fetchStub = sandbox + .stub(self, 'fetch') + .resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -140,7 +142,7 @@ describe(`NetworkOnly`, function() { expect(fetchStub.calledWith(request, fetchOptions)).to.be.true; }); - it(`should throw if the network request times out`, async function() { + it(`should throw if the network request times out`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -149,8 +151,9 @@ describe(`NetworkOnly`, function() { // Note Sinon fake timers do not work with `await timeout()` used // in the current `StrategyHandler` implementation. const networkTimeoutSeconds = 0.5; - const sleepLongerThanNetworkTimeout = - sleep(2 * networkTimeoutSeconds * 1000); + const sleepLongerThanNetworkTimeout = sleep( + 2 * networkTimeoutSeconds * 1000, + ); sandbox.stub(self, 'fetch').callsFake(async () => { await sleepLongerThanNetworkTimeout; @@ -160,11 +163,11 @@ describe(`NetworkOnly`, function() { const networkOnly = new NetworkOnly({networkTimeoutSeconds}); await expectError( - () => networkOnly.handle({event, request}), - 'no-response', - (err) => { - expect(err.details.error.message).to.include(networkTimeoutSeconds); - }, + () => networkOnly.handle({event, request}), + 'no-response', + (err) => { + expect(err.details.error.message).to.include(networkTimeoutSeconds); + }, ); }); }); diff --git a/test/workbox-strategies/sw/test-StaleWhileRevalidate.mjs b/test/workbox-strategies/sw/test-StaleWhileRevalidate.mjs index 629449d97..a451a927a 100644 --- a/test/workbox-strategies/sw/test-StaleWhileRevalidate.mjs +++ b/test/workbox-strategies/sw/test-StaleWhileRevalidate.mjs @@ -9,28 +9,30 @@ import {cacheNames} from 'workbox-core/_private/cacheNames.mjs'; import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.mjs'; import {compareResponses} from '../../../infra/testing/helpers/compareResponses.mjs'; -import {eventDoneWaiting, spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; +import { + eventDoneWaiting, + spyOnEvent, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import {generateOpaqueResponse} from '../../../infra/testing/helpers/generateOpaqueResponse.mjs'; import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; - -describe(`StaleWhileRevalidate`, function() { +describe(`StaleWhileRevalidate`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - after(async function() { + after(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe(`handle()`, function() { - it(`should add the initial response to the cache`, async function() { + describe(`handle()`, function () { + it(`should add the initial response to the cache`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); @@ -51,7 +53,7 @@ describe(`StaleWhileRevalidate`, function() { await compareResponses(cachedResponse, handleResponse, true); }); - it(`should support using a string as the request`, async function() { + it(`should support using a string as the request`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); const stringRequest = 'http://example.io/test/'; @@ -73,7 +75,7 @@ describe(`StaleWhileRevalidate`, function() { await compareResponses(cachedResponse, handleResponse, true); }); - it(`should return the cached response and not update the cache when the network request fails`, async function() { + it(`should return the cached response and not update the cache when the network request fails`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -98,7 +100,7 @@ describe(`StaleWhileRevalidate`, function() { await compareResponses(firstCachedResponse, secondCachedResponse, true); }); - it(`should return the cached response and update the cache when the network request succeeds`, async function() { + it(`should return the cached response and update the cache when the network request succeeds`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); @@ -109,7 +111,6 @@ describe(`StaleWhileRevalidate`, function() { const cache = await caches.open(cacheNames.getRuntimeName()); await cache.put(request, firstCachedResponse.clone()); - const staleWhileRevalidate = new StaleWhileRevalidate(); const handleResponse = await staleWhileRevalidate.handle({ request, @@ -123,7 +124,7 @@ describe(`StaleWhileRevalidate`, function() { await compareResponses(firstCachedResponse, secondCachedResponse, false); }); - it(`should update the cache with an the opaque cross-origin network response`, async function() { + it(`should update the cache with an the opaque cross-origin network response`, async function () { const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -146,7 +147,7 @@ describe(`StaleWhileRevalidate`, function() { expect(cachedResponse.status).to.eql(0); }); - it(`should allow adding plugins to override cacheOkAndOpaque`, function() { + it(`should allow adding plugins to override cacheOkAndOpaque`, function () { const plugins = [ { cacheWillUpdate: () => {}, @@ -158,11 +159,13 @@ describe(`StaleWhileRevalidate`, function() { expect(staleWhileRevalidate.plugins).to.equal(plugins); }); - it(`should use the fetchOptions provided`, async function() { + it(`should use the fetchOptions provided`, async function () { const fetchOptions = {credentials: 'include'}; const staleWhileRevalidate = new StaleWhileRevalidate({fetchOptions}); - const fetchStub = sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); + const fetchStub = sandbox + .stub(self, 'fetch') + .resolves(generateUniqueResponse()); const request = new Request('http://example.io/test/'); const event = new FetchEvent('fetch', {request}); spyOnEvent(event); @@ -178,11 +181,12 @@ describe(`StaleWhileRevalidate`, function() { expect(fetchStub.calledWith(request, fetchOptions)).to.be.true; }); - it(`should use the CacheQueryOptions when performing a cache match`, async function() { + it(`should use the CacheQueryOptions when performing a cache match`, async function () { sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); - const matchStub = sandbox.stub(self.caches.constructor.prototype, 'match') - .resolves(generateUniqueResponse()); + const matchStub = sandbox + .stub(self.caches.constructor.prototype, 'match') + .resolves(generateUniqueResponse()); const matchOptions = {ignoreSearch: true}; const staleWhileRevalidate = new StaleWhileRevalidate({matchOptions}); @@ -203,7 +207,7 @@ describe(`StaleWhileRevalidate`, function() { expect(matchStub.firstCall.args[1].ignoreSearch).to.equal(true); }); - it(`should throw an error when the network request fails, and there's no cache match`, async function() { + it(`should throw an error when the network request fails, and there's no cache match`, async function () { sandbox.stub(self, 'fetch').rejects(new Error('Injected error.')); const request = new Request('http://example.io/test/'); @@ -212,11 +216,12 @@ describe(`StaleWhileRevalidate`, function() { const staleWhileRevalidate = new StaleWhileRevalidate(); await expectError( - () => staleWhileRevalidate.handle({ + () => + staleWhileRevalidate.handle({ request, event, }), - 'no-response', + 'no-response', ); await eventDoneWaiting(event); diff --git a/test/workbox-strategies/sw/test-Strategy.mjs b/test/workbox-strategies/sw/test-Strategy.mjs index 133bfe3e3..52d8494f3 100644 --- a/test/workbox-strategies/sw/test-Strategy.mjs +++ b/test/workbox-strategies/sw/test-Strategy.mjs @@ -10,7 +10,6 @@ import {timeout} from 'workbox-core/_private/timeout.mjs'; import {Strategy} from 'workbox-strategies/Strategy.mjs'; import {spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; - class FetchStrategy extends Strategy { _handle(request, handler) { return handler.fetch(request); @@ -66,8 +65,10 @@ class ExtendingStrategy extends FetchStrategy { } async _handle(request, handler) { handler.waitUntil(timeout(100)); - return await handler.cacheMatch(request) || - await super._handle(request, handler); + return ( + (await handler.cacheMatch(request)) || + (await super._handle(request, handler)) + ); } } @@ -79,30 +80,32 @@ function generateOptions() { return {request, event}; } -describe(`Strategy`, function() { +describe(`Strategy`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - afterEach(async function() { + afterEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe('constructor()', function() { - it('works when extended but not overridden', function() { + describe('constructor()', function () { + it('works when extended but not overridden', function () { const options = { cacheName: 'test-cache', fetchOptions: {credentials: 'include'}, matchOptions: {ignoreSearch: true}, - plugins: [{ - handlerWillStart() {}, - }], + plugins: [ + { + handlerWillStart() {}, + }, + ], }; const strategy = new FetchStrategy(options); @@ -113,14 +116,16 @@ describe(`Strategy`, function() { expect(strategy.plugins).to.equal(options.plugins); }); - it('works when extended and overridden', function() { + it('works when extended and overridden', function () { const options = { cacheName: 'test-cache', fetchOptions: {credentials: 'include'}, matchOptions: {ignoreSearch: true}, - plugins: [{ - handlerWillStart() {}, - }], + plugins: [ + { + handlerWillStart() {}, + }, + ], newProperty: 'I am new!', }; @@ -135,13 +140,16 @@ describe(`Strategy`, function() { }); }); - describe('.handleAll()', function() { - it('runs the strategy and returns a response and done promise tuple', async function() { + describe('.handleAll()', function () { + it('runs the strategy and returns a response and done promise tuple', async function () { const strategy = new LongWaitUntilStrategy(); const {request, event} = generateOptions(); const startTime = performance.now(); - const [responsePromise, donePromise] = strategy.handleAll({request, event}); + const [responsePromise, donePromise] = strategy.handleAll({ + request, + event, + }); const response = await responsePromise; expect(performance.now() - startTime < 200).to.be.true; @@ -151,7 +159,7 @@ describe(`Strategy`, function() { expect(performance.now() - startTime >= 200).to.be.true; }); - it('accepts a string as the request param', async function() { + it('accepts a string as the request param', async function () { sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); const strategy = new FetchStrategy(); @@ -163,11 +171,12 @@ describe(`Strategy`, function() { }); await responsePromise; - expect(self.fetch.firstCall.args[0].url) - .to.equal(location.origin + '/string-url'); + expect(self.fetch.firstCall.args[0].url).to.equal( + location.origin + '/string-url', + ); }); - it('accepts a Request as the request param', async function() { + it('accepts a Request as the request param', async function () { sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); const strategy = new FetchStrategy(); @@ -179,11 +188,13 @@ describe(`Strategy`, function() { expect(self.fetch.firstCall.args[0]).to.equal(request); }); - it(`runs all handlerWillStart callbacks`, async function() { + it(`runs all handlerWillStart callbacks`, async function () { const plugins = [ {handlerWillStart: sandbox.spy()}, {nonMatchingCallback: sandbox.spy()}, - {/* Empty plugin */}, + { + /* Empty plugin */ + }, {handlerWillStart: sandbox.spy()}, ]; const strategy = new EmptyStrategy({plugins}); @@ -191,96 +202,156 @@ describe(`Strategy`, function() { await Promise.all(strategy.handleAll({request, event})); - expect(plugins[0].handlerWillStart.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; + expect( + plugins[0].handlerWillStart.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; expect(plugins[1].nonMatchingCallback.callCount).to.equal(0); - expect(plugins[3].handlerWillStart.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; + expect( + plugins[3].handlerWillStart.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; }); - it(`runs all handlerWillRespond callbacks with the response`, async function() { + it(`runs all handlerWillRespond callbacks with the response`, async function () { const plugins = [ - {handlerWillRespond: sandbox.stub().callsFake(({response}) => response)}, + { + handlerWillRespond: sandbox + .stub() + .callsFake(({response}) => response), + }, {nonMatchingCallback: sandbox.spy()}, - {/* Empty plugin */}, - {handlerWillRespond: sandbox.stub().callsFake(({response}) => response)}, + { + /* Empty plugin */ + }, + { + handlerWillRespond: sandbox + .stub() + .callsFake(({response}) => response), + }, ]; const strategy = new EmptyStrategy({plugins}); const {request, event} = generateOptions(); - const [response] = await Promise.all(strategy.handleAll({request, event})); - - expect(plugins[0].handlerWillRespond.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[0].handlerWillRespond.firstCall.args[0].response - .clone().text()).to.equal('generated response'); - expect(await plugins[0].handlerWillRespond.firstCall.returnValue - .clone().text()).to.equal('generated response'); + const [response] = await Promise.all( + strategy.handleAll({request, event}), + ); + + expect( + plugins[0].handlerWillRespond.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[0].handlerWillRespond.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); + expect( + await plugins[0].handlerWillRespond.firstCall.returnValue + .clone() + .text(), + ).to.equal('generated response'); expect(plugins[1].nonMatchingCallback.callCount).to.equal(0); - expect(plugins[3].handlerWillRespond.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[3].handlerWillRespond.firstCall.args[0].response - .clone().text()).to.equal('generated response'); - expect(await plugins[3].handlerWillRespond.firstCall.returnValue - .clone().text()).to.equal('generated response'); + expect( + plugins[3].handlerWillRespond.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[3].handlerWillRespond.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); + expect( + await plugins[3].handlerWillRespond.firstCall.returnValue + .clone() + .text(), + ).to.equal('generated response'); expect(await response.clone().text()).to.equal('generated response'); }); - it(`runs all handlerDidRespond callbacks with the response`, async function() { + it(`runs all handlerDidRespond callbacks with the response`, async function () { const plugins = [ {handlerDidRespond: sandbox.spy()}, {nonMatchingCallback: sandbox.spy()}, - {/* Empty plugin */}, + { + /* Empty plugin */ + }, {handlerDidRespond: sandbox.spy()}, ]; const strategy = new EmptyStrategy({plugins}); const {request, event} = generateOptions(); - const [response] = await Promise.all(strategy.handleAll({request, event})); - - expect(plugins[0].handlerDidRespond.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[0].handlerDidRespond.firstCall.args[0].response - .clone().text()).to.equal('generated response'); + const [response] = await Promise.all( + strategy.handleAll({request, event}), + ); + + expect( + plugins[0].handlerDidRespond.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[0].handlerDidRespond.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); expect(plugins[1].nonMatchingCallback.callCount).to.equal(0); - expect(plugins[3].handlerDidRespond.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[3].handlerDidRespond.firstCall.args[0].response - .clone().text()).to.equal('generated response'); + expect( + plugins[3].handlerDidRespond.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[3].handlerDidRespond.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); expect(await response.clone().text()).to.equal('generated response'); }); - it(`runs all handlerDidComplete callbacks`, async function() { + it(`runs all handlerDidComplete callbacks`, async function () { const plugins = [ {handlerDidComplete: sandbox.spy()}, {nonMatchingCallback: sandbox.spy()}, - {/* Empty plugin */}, + { + /* Empty plugin */ + }, {handlerDidComplete: sandbox.spy()}, ]; const strategy = new EmptyStrategy({plugins}); @@ -288,27 +359,41 @@ describe(`Strategy`, function() { await Promise.all(strategy.handleAll({request, event})); - expect(plugins[0].handlerDidComplete.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[0].handlerDidComplete.firstCall.args[0].response - .clone().text()).to.equal('generated response'); + expect( + plugins[0].handlerDidComplete.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[0].handlerDidComplete.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); expect(plugins[1].nonMatchingCallback.callCount).to.equal(0); - expect(plugins[3].handlerDidComplete.calledOnceWith(sinon.match({ - request, - event, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[3].handlerDidComplete.firstCall.args[0].response - .clone().text()).to.equal('generated response'); + expect( + plugins[3].handlerDidComplete.calledOnceWith( + sinon.match({ + request, + event, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[3].handlerDidComplete.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); }); - it('passes any errors in waitUntil promises to the handlerDidComplete callback', async function() { - const plugins =[{handlerDidComplete: sinon.spy()}]; + it('passes any errors in waitUntil promises to the handlerDidComplete callback', async function () { + const plugins = [{handlerDidComplete: sinon.spy()}]; const strategy = new ErrorStrategy({plugins}); const {request, event} = generateOptions(); @@ -321,26 +406,37 @@ describe(`Strategy`, function() { doneError = error; } - expect(plugins[0].handlerDidComplete.calledOnceWith(sinon.match({ - request, - event, - error: doneError, - state: sinon.match(Object), - }))).to.be.true; - expect(await plugins[0].handlerDidComplete.firstCall.args[0].response - .clone().text()).to.equal('generated response'); + expect( + plugins[0].handlerDidComplete.calledOnceWith( + sinon.match({ + request, + event, + error: doneError, + state: sinon.match(Object), + }), + ), + ).to.be.true; + expect( + await plugins[0].handlerDidComplete.firstCall.args[0].response + .clone() + .text(), + ).to.equal('generated response'); }); }); - describe('handlerDidError', function() { - it('should use the first callback that returns a Response when _handler() throws', async function() { - const plugins = [{ - handlerDidError: sandbox.stub().resolves(undefined), - }, { - handlerDidError: sandbox.stub().resolves(new Response('from plugin')), - }, { - handlerDidError: sandbox.stub().resolves(undefined), - }]; + describe('handlerDidError', function () { + it('should use the first callback that returns a Response when _handler() throws', async function () { + const plugins = [ + { + handlerDidError: sandbox.stub().resolves(undefined), + }, + { + handlerDidError: sandbox.stub().resolves(new Response('from plugin')), + }, + { + handlerDidError: sandbox.stub().resolves(undefined), + }, + ]; const error = new Error('thrown error'); const strategy = new HandlerThrowsStrategy({error, plugins}); @@ -349,12 +445,16 @@ describe(`Strategy`, function() { const [responsePromise] = strategy.handleAll({request, event}); const response = await responsePromise; const responseBody = await response.text(); - const expectedArgs = [[{ - error, - event, - request, - state: {}, - }]]; + const expectedArgs = [ + [ + { + error, + event, + request, + state: {}, + }, + ], + ]; expect(responseBody).to.eql('from plugin'); expect(plugins[0].handlerDidError.args).to.eql(expectedArgs); @@ -363,12 +463,15 @@ describe(`Strategy`, function() { expect(plugins[2].handlerDidError.args).to.eql([]); }); - it(`should rethrow the error when the callbacks don't return a Response`, async function() { - const plugins = [{ - handlerDidError: sandbox.stub().resolves(undefined), - }, { - handlerDidError: sandbox.stub().resolves(undefined), - }]; + it(`should rethrow the error when the callbacks don't return a Response`, async function () { + const plugins = [ + { + handlerDidError: sandbox.stub().resolves(undefined), + }, + { + handlerDidError: sandbox.stub().resolves(undefined), + }, + ]; const error = new Error('thrown error'); const strategy = new HandlerThrowsStrategy({error, plugins}); @@ -381,22 +484,28 @@ describe(`Strategy`, function() { } catch (thrownError) { expect(thrownError).to.eql(error); - const expectedArgs = [[{ - error, - event, - request, - state: {}, - }]]; + const expectedArgs = [ + [ + { + error, + event, + request, + state: {}, + }, + ], + ]; expect(plugins[0].handlerDidError.args).to.eql(expectedArgs); expect(plugins[1].handlerDidError.args).to.eql(expectedArgs); } }); - it('should use the callback Response when _handler() returns undefined', async function() { - const plugins = [{ - handlerDidError: sandbox.stub().resolves(new Response('from plugin')), - }]; + it('should use the callback Response when _handler() returns undefined', async function () { + const plugins = [ + { + handlerDidError: sandbox.stub().resolves(new Response('from plugin')), + }, + ]; const strategy = new HandlerReturnsUndefinedStrategy({plugins}); const {request, event} = generateOptions(); @@ -409,13 +518,17 @@ describe(`Strategy`, function() { // We can't do a deep equality check without a reference to the // WorkboxError, so just do a sanity check. - expect(plugins[0].handlerDidError.args[0][0].error.name).to.eql('no-response'); + expect(plugins[0].handlerDidError.args[0][0].error.name).to.eql( + 'no-response', + ); }); - it('should throw an error when _handler() returns undefined and the callbacks return undefined', async function() { - const plugins = [{ - handlerDidError: sandbox.stub().resolves(undefined), - }]; + it('should throw an error when _handler() returns undefined and the callbacks return undefined', async function () { + const plugins = [ + { + handlerDidError: sandbox.stub().resolves(undefined), + }, + ]; const strategy = new HandlerReturnsUndefinedStrategy({plugins}); const {request, event} = generateOptions(); @@ -427,19 +540,25 @@ describe(`Strategy`, function() { } catch (thrownError) { expect(thrownError.name).to.eql('no-response'); - expect(plugins[0].handlerDidError.args).to.eql([[{ - event, - request, - error: thrownError, - state: {}, - }]]); + expect(plugins[0].handlerDidError.args).to.eql([ + [ + { + event, + request, + error: thrownError, + state: {}, + }, + ], + ]); } }); - it('should use the callback Response when _handler() returns Response.error()', async function() { - const plugins = [{ - handlerDidError: sandbox.stub().resolves(new Response('from plugin')), - }]; + it('should use the callback Response when _handler() returns Response.error()', async function () { + const plugins = [ + { + handlerDidError: sandbox.stub().resolves(new Response('from plugin')), + }, + ]; const strategy = new HandlerReturnsResponseErrorStrategy({plugins}); const {request, event} = generateOptions(); @@ -452,20 +571,21 @@ describe(`Strategy`, function() { // We can't do a deep equality check without a reference to the // WorkboxError, so just do a sanity check. - expect(plugins[0].handlerDidError.args[0][0].error.name).to.eql('no-response'); + expect(plugins[0].handlerDidError.args[0][0].error.name).to.eql( + 'no-response', + ); }); }); - describe('handle', function() { - it(`invokes handleAll() and returns the response promise`, async function() { + describe('handle', function () { + it(`invokes handleAll() and returns the response promise`, async function () { const strategy = new EmptyStrategy(); const {request, event} = generateOptions(); const stubResponse = new Response('stub response'); - sandbox.stub(strategy, 'handleAll').returns([ - Promise.resolve(stubResponse), - Promise.resolve(), - ]); + sandbox + .stub(strategy, 'handleAll') + .returns([Promise.resolve(stubResponse), Promise.resolve()]); const response = await strategy.handle({request, event}); diff --git a/test/workbox-strategies/sw/test-StrategyHandler.mjs b/test/workbox-strategies/sw/test-StrategyHandler.mjs index b03e56aa2..8d6f165eb 100644 --- a/test/workbox-strategies/sw/test-StrategyHandler.mjs +++ b/test/workbox-strategies/sw/test-StrategyHandler.mjs @@ -13,7 +13,10 @@ import {Strategy} from 'workbox-strategies/Strategy.mjs'; import {StrategyHandler} from 'workbox-strategies/StrategyHandler.mjs'; import {timeout} from 'workbox-core/_private/timeout.mjs'; -import {spyOnEvent, eventDoneWaiting} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; +import { + spyOnEvent, + eventDoneWaiting, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; class TestStrategy extends Strategy { _handle() { @@ -40,40 +43,48 @@ const createStrategyHandler = (options) => { }); }; -describe(`StrategyHandler`, function() { +describe(`StrategyHandler`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - afterEach(async function() { + afterEach(async function () { const keys = await caches.keys(); await Promise.all(keys.map((key) => caches.delete(key))); sandbox.restore(); }); - describe('constructor()', function() { - it(`should throw when called without an 'event' parameter in dev`, async function() { + describe('constructor()', function () { + it(`should throw when called without an 'event' parameter in dev`, async function () { if (process.env.NODE_ENV === 'production') { return this.skip(); } await expectError( - () => new StrategyHandler(new TestStrategy(), {}), - 'incorrect-class', - (error) => { - expect(error.details).to.have.property('moduleName').that.equals('workbox-strategies'); - expect(error.details).to.have.property('className').that.equals('StrategyHandler'); - expect(error.details).to.have.property('funcName').that.equals('constructor'); - expect(error.details).to.have.property('paramName').that.equals('options.event'); - }, + () => new StrategyHandler(new TestStrategy(), {}), + 'incorrect-class', + (error) => { + expect(error.details) + .to.have.property('moduleName') + .that.equals('workbox-strategies'); + expect(error.details) + .to.have.property('className') + .that.equals('StrategyHandler'); + expect(error.details) + .to.have.property('funcName') + .that.equals('constructor'); + expect(error.details) + .to.have.property('paramName') + .that.equals('options.event'); + }, ); }); - it('creates an object with the correct public properties', function() { + it('creates an object with the correct public properties', function () { const handler = createStrategyHandler(); expect(handler.request).to.be.instanceOf(Request); @@ -82,16 +93,18 @@ describe(`StrategyHandler`, function() { expect(handler.params).to.be.instanceOf(Object); }); - it('passes a deferred to event waitUntil (if passed an event)', function() { + it('passes a deferred to event waitUntil (if passed an event)', function () { const handler = createStrategyHandler(); expect(handler.event.waitUntil.callCount).to.equal(1); - expect(handler.event.waitUntil.firstCall.args[0]).to.be.instanceOf(Promise); + expect(handler.event.waitUntil.firstCall.args[0]).to.be.instanceOf( + Promise, + ); }); }); - describe('waitUntil()', function() { - it('adds promises to an internal queue', function() { + describe('waitUntil()', function () { + it('adds promises to an internal queue', function () { const handler = createStrategyHandler(); handler.waitUntil(Promise.resolve()); @@ -102,7 +115,7 @@ describe(`StrategyHandler`, function() { expect(handler._extendLifetimePromises).to.have.lengthOf(3); }); - it('returns the passed promise', function() { + it('returns the passed promise', function () { const handler = createStrategyHandler(); const promise = Promise.resolve(); @@ -110,8 +123,8 @@ describe(`StrategyHandler`, function() { }); }); - describe('doneWaiting()', function() { - it('returns a promise the resolves once all waitUntil promises have settled', async function() { + describe('doneWaiting()', function () { + it('returns a promise the resolves once all waitUntil promises have settled', async function () { const handler = createStrategyHandler(); const spy = sandbox.spy(); @@ -127,8 +140,8 @@ describe(`StrategyHandler`, function() { }); }); - describe('destroy()', function() { - it('resolves any waitUntil promises immediately', function(done) { + describe('destroy()', function () { + it('resolves any waitUntil promises immediately', function (done) { const handler = createStrategyHandler(); const deferred = new Deferred(); @@ -147,8 +160,8 @@ describe(`StrategyHandler`, function() { // These tests were copied from `test-fetchWrapper` to ensure we don't // lose any of the existing behavior in the update. - describe(`fetch()`, function() { - it(`should work with request string`, async function() { + describe(`fetch()`, function () { + it(`should work with request string`, async function () { const stub = sandbox.stub(self, 'fetch').callsFake(() => new Response()); const handler = createStrategyHandler(); @@ -159,7 +172,7 @@ describe(`StrategyHandler`, function() { expect(fetchRequest.url).to.equal(`${location.origin}/test/string`); }); - it(`should work with Request instance`, async function() { + it(`should work with Request instance`, async function () { const stub = sandbox.stub(self, 'fetch').callsFake(() => new Response()); const handler = createStrategyHandler(); @@ -170,13 +183,13 @@ describe(`StrategyHandler`, function() { expect(fetchRequest.url).to.equal(`${location.origin}/test/response`); }); - it(`should use fetchOptions from the strategy`, async function() { + it(`should use fetchOptions from the strategy`, async function () { const stub = sandbox.stub(self, 'fetch').callsFake(() => new Response()); const fetchOptions = { method: 'POST', headers: { - 'Custom': 'Header', + Custom: 'Header', }, body: 'Example Body', }; @@ -190,7 +203,7 @@ describe(`StrategyHandler`, function() { expect(fetchArgs[1]).to.deep.equal(fetchOptions); }); - it(`should ignore fetchOptions when request.mode === 'navigate'`, async function() { + it(`should ignore fetchOptions when request.mode === 'navigate'`, async function () { // See https://github.com/GoogleChrome/workbox/issues/1796 const fetchStub = sandbox.stub(self, 'fetch').resolves(new Response()); @@ -215,11 +228,17 @@ describe(`StrategyHandler`, function() { expect(fetchStub.firstCall.args[1]).not.to.exist; }); - it(`should call the requestWillFetch callback in all strategy plugins and use the returned request`, async function() { - const fetchStub = sandbox.stub(self, 'fetch').callsFake(() => new Response()); + it(`should call the requestWillFetch callback in all strategy plugins and use the returned request`, async function () { + const fetchStub = sandbox + .stub(self, 'fetch') + .callsFake(() => new Response()); - const stub1 = sandbox.stub().returns(new Request('/test/requestWillFetch/1')); - const stub2 = sandbox.stub().returns(new Request('/test/requestWillFetch/2')); + const stub1 = sandbox + .stub() + .returns(new Request('/test/requestWillFetch/1')); + const stub2 = sandbox + .stub() + .returns(new Request('/test/requestWillFetch/2')); const firstPlugin = {requestWillFetch: stub1}; const secondPlugin = {requestWillFetch: stub2}; @@ -231,20 +250,28 @@ describe(`StrategyHandler`, function() { await handler.fetch('/test/requestWillFetch/0'); expect(stub1.callCount).equal(1); - expect(stub1.args[0][0].request.url).to.equal(`${location.origin}/test/requestWillFetch/0`); + expect(stub1.args[0][0].request.url).to.equal( + `${location.origin}/test/requestWillFetch/0`, + ); expect(stub1.args[0][0].event).to.equal(handler.event); expect(stub2.callCount).equal(1); - expect(stub2.args[0][0].request.url).to.equal(`${location.origin}/test/requestWillFetch/1`); + expect(stub2.args[0][0].request.url).to.equal( + `${location.origin}/test/requestWillFetch/1`, + ); expect(stub2.args[0][0].event).to.equal(handler.event); expect(fetchStub.callCount).to.equal(1); const fetchRequest = fetchStub.args[0][0]; - expect(fetchRequest.url).to.equal(`${location.origin}/test/requestWillFetch/2`); + expect(fetchRequest.url).to.equal( + `${location.origin}/test/requestWillFetch/2`, + ); }); - it(`should throw a meaningful error on bad requestWillFetch plugin`, async function() { - const fetchStub = sandbox.stub(self, 'fetch').callsFake(() => new Response()); + it(`should throw a meaningful error on bad requestWillFetch plugin`, async function () { + const fetchStub = sandbox + .stub(self, 'fetch') + .callsFake(() => new Response()); const errorPlugin = { requestWillFetch: (request) => { throw new Error('Injected Error from Test.'); @@ -256,41 +283,59 @@ describe(`StrategyHandler`, function() { plugins: [errorPlugin], }); - await expectError(() => { - return handler.fetch('/test/requestWillFetch/0'); - }, 'plugin-error-request-will-fetch', (err) => { - expect(err.details.thrownErrorMessage).to.exist; - expect(err.details.thrownErrorMessage).to.equal('Injected Error from Test.'); - }); + await expectError( + () => { + return handler.fetch('/test/requestWillFetch/0'); + }, + 'plugin-error-request-will-fetch', + (err) => { + expect(err.details.thrownErrorMessage).to.exist; + expect(err.details.thrownErrorMessage).to.equal( + 'Injected Error from Test.', + ); + }, + ); expect(errorPluginSpy.callCount).equal(1); expect(fetchStub.callCount).to.equal(0); }); - it(`should call fetchDidFail method in plugins`, async function() { + it(`should call fetchDidFail method in plugins`, async function () { sandbox.stub(self, 'fetch').callsFake(() => { return Promise.reject(new Error('Injected Error.')); }); const secondPlugin = { - fetchDidFail: sandbox.stub().callsFake(({originalRequest, request, event, error}) => { - expect(originalRequest.url).to.equal(`${location.origin}/test/failingRequest/0`); - expect(request.url).to.equal(`${location.origin}/test/failingRequest/1`); - expect(error.message).to.equal('Injected Error.'); - }), + fetchDidFail: sandbox + .stub() + .callsFake(({originalRequest, request, event, error}) => { + expect(originalRequest.url).to.equal( + `${location.origin}/test/failingRequest/0`, + ); + expect(request.url).to.equal( + `${location.origin}/test/failingRequest/1`, + ); + expect(error.message).to.equal('Injected Error.'); + }), }; const firstPlugin = { requestWillFetch: ({request}) => { return new Request('/test/failingRequest/1'); }, - fetchDidFail: sandbox.stub().callsFake(({originalRequest, request, event, error}) => { - // This should be called first - expect(secondPlugin.fetchDidFail.callCount).to.equal(0); - expect(originalRequest.url).to.equal(`${location.origin}/test/failingRequest/0`); - expect(request.url).to.equal(`${location.origin}/test/failingRequest/1`); - expect(error.message).to.equal('Injected Error.'); - }), + fetchDidFail: sandbox + .stub() + .callsFake(({originalRequest, request, event, error}) => { + // This should be called first + expect(secondPlugin.fetchDidFail.callCount).to.equal(0); + expect(originalRequest.url).to.equal( + `${location.origin}/test/failingRequest/0`, + ); + expect(request.url).to.equal( + `${location.origin}/test/failingRequest/1`, + ); + expect(error.message).to.equal('Injected Error.'); + }), }; const handler = createStrategyHandler({ @@ -315,17 +360,21 @@ describe(`StrategyHandler`, function() { expect(self.fetch.callCount).to.equal(1); const fetchRequest = self.fetch.args[0][0]; - expect(fetchRequest.url).to.equal(`${location.origin}/test/failingRequest/1`); + expect(fetchRequest.url).to.equal( + `${location.origin}/test/failingRequest/1`, + ); }); - it(`should call the fetchDidSucceed method in plugins`, async function() { + it(`should call the fetchDidSucceed method in plugins`, async function () { const originalRequest = new Request('/testing'); - sandbox.stub(self, 'fetch').resolves(new Response('', { - headers: { - 'x-count': 1, - }, - })); + sandbox.stub(self, 'fetch').resolves( + new Response('', { + headers: { + 'x-count': 1, + }, + }), + ); const fetchDidSucceed = sandbox.stub().callsFake(({response}) => { const count = Number(response.headers.get('x-count')); @@ -361,8 +410,8 @@ describe(`StrategyHandler`, function() { // These tests were copied from `test-cacheWrapper` to ensure we don't // lose any of the existing behavior in the update. - describe(`.cachePut()`, function() { - it(`should work with a request and response`, async function() { + describe(`.cachePut()`, function () { + it(`should work with a request and response`, async function () { const testCache = await caches.open('TEST-CACHE'); const cacheOpenStub = sandbox.stub(self.caches, 'open'); const cachePutStub = sandbox.stub(testCache, 'put'); @@ -388,10 +437,12 @@ describe(`StrategyHandler`, function() { // This covers opaque responses (0) and partial content responses (206). for (const status of [0, 206]) { - it(`should not cache response.status of ${status} by default`, async function() { + it(`should not cache response.status of ${status} by default`, async function () { const cacheName = 'test-cache'; const testCache = await caches.open(cacheName); - const cacheOpenStub = sandbox.stub(self.caches, 'open').resolves(testCache); + const cacheOpenStub = sandbox + .stub(self.caches, 'open') + .resolves(testCache); const cachePutSpy = sandbox.spy(testCache, 'put'); const putRequest = new Request('/test/string'); @@ -409,7 +460,7 @@ describe(`StrategyHandler`, function() { }); } - it(`should throw when trying to cache POST requests in dev mode`, async function() { + it(`should throw when trying to cache POST requests in dev mode`, async function () { if (process.env.NODE_ENV === 'production') this.skip(); const testCache = await caches.open('TEST-CACHE'); @@ -433,7 +484,7 @@ describe(`StrategyHandler`, function() { expect(cachePutStub.callCount).to.equal(0); }); - it(`should log when caching a response with a Vary: header in dev mode`, async function() { + it(`should log when caching a response with a Vary: header in dev mode`, async function () { if (process.env.NODE_ENV === 'production') { this.skip(); } @@ -452,7 +503,7 @@ describe(`StrategyHandler`, function() { expect(loggerSpy.firstCall.args[0]).to.include('ignoreVary'); }); - it(`should call cacheDidUpdate`, async function() { + it(`should call cacheDidUpdate`, async function () { const firstPlugin = { cacheDidUpdate: () => {}, }; @@ -482,22 +533,26 @@ describe(`StrategyHandler`, function() { await handler.cachePut(putRequest, putResponse); - [spyOne, spyTwo].forEach((pluginSpy) => { expect(pluginSpy.callCount).to.equal(1); expect(pluginSpy.args[0][0].cacheName).to.equal('TODO-CHANGE-ME'); expect(pluginSpy.args[0][0].request).to.equal(putRequest); expect(pluginSpy.args[0][0].oldResponse).to.equal(undefined); // `newResponse` is cloned, so don't compare for object equality. - expect(pluginSpy.args[0][0].newResponse.headers.get('x-id')).to.equal('1'); + expect(pluginSpy.args[0][0].newResponse.headers.get('x-id')).to.equal( + '1', + ); // Reset so the spies are clean for next step in the test. pluginSpy.resetHistory(); }); - const putResponseUpdate = new Response('Response for /test/string number 2', { - headers: {'x-id': '2'}, - }); + const putResponseUpdate = new Response( + 'Response for /test/string number 2', + { + headers: {'x-id': '2'}, + }, + ); await handler.cachePut(putRequest, putResponseUpdate); @@ -507,12 +562,16 @@ describe(`StrategyHandler`, function() { expect(pluginSpy.args[0][0].request).to.equal(putRequest); // `oldResponse` and `newResponse` are cloned, // so don't compare for object equality. - expect(pluginSpy.args[0][0].oldResponse.headers.get('x-id')).to.equal('1'); - expect(pluginSpy.args[0][0].newResponse.headers.get('x-id')).to.equal('2'); + expect(pluginSpy.args[0][0].oldResponse.headers.get('x-id')).to.equal( + '1', + ); + expect(pluginSpy.args[0][0].newResponse.headers.get('x-id')).to.equal( + '2', + ); }); }); - it(`should call cacheWillUpdate`, async function() { + it(`should call cacheWillUpdate`, async function () { const firstPluginResponse = new Response('Response for /test/string/1'); const firstPlugin = { cacheWillUpdate: () => { @@ -547,20 +606,28 @@ describe(`StrategyHandler`, function() { expect(spyOne.callCount).to.equal(1); - expect(spyOne.calledWith(sinon.match({ - request: putRequest, - response: putResponse, - event: handler.event, - }))).to.be.true; + expect( + spyOne.calledWith( + sinon.match({ + request: putRequest, + response: putResponse, + event: handler.event, + }), + ), + ).to.be.true; expect(spyTwo.callCount).to.equal(1); - expect(spyTwo.calledWith(sinon.match({ - request: putRequest, - response: firstPluginResponse, - event: handler.event, - }))).to.be.true; + expect( + spyTwo.calledWith( + sinon.match({ + request: putRequest, + response: firstPluginResponse, + event: handler.event, + }), + ), + ).to.be.true; }); - it(`should call cacheKeyWillBeUsed`, async function() { + it(`should call cacheKeyWillBeUsed`, async function () { const cacheName = 'cacheKeyWillBeUsed-test-cache'; const cache = await caches.open(cacheName); sandbox.stub(caches, 'open').resolves(cache); @@ -593,25 +660,35 @@ describe(`StrategyHandler`, function() { await handler.cachePut(initialRequest, response); - expect(spyOne.calledOnceWith(sinon.match({ - mode: 'write', - request: initialRequest, - }))).to.be.true; + expect( + spyOne.calledOnceWith( + sinon.match({ + mode: 'write', + request: initialRequest, + }), + ), + ).to.be.true; expect(spyOne.thisValues[0]).to.eql(firstPlugin); - expect(spyTwo.calledOnceWith(sinon.match({ - mode: 'write', - request: firstPluginReturnValue, - }))).to.be.true; + expect( + spyTwo.calledOnceWith( + sinon.match({ + mode: 'write', + request: firstPluginReturnValue, + }), + ), + ).to.be.true; expect(spyTwo.thisValues[0]).to.eql(secondPlugin); expect(cachePutStub.calledOnce).to.be.true; // Check the url of the Request passed to cache.put(). - expect(cachePutStub.args[0][0].url).to.eql(`${self.location.origin}/secondPlugin`); + expect(cachePutStub.args[0][0].url).to.eql( + `${self.location.origin}/secondPlugin`, + ); expect(cachePutStub.args[0][1]).to.eql(response); }); - it(`should allow caching of posts if cacheKeyWillBeUsed returns a get request`, async function() { + it(`should allow caching of posts if cacheKeyWillBeUsed returns a get request`, async function () { const cacheName = 'cacheKeyWillBeUsed-test-cache'; const cache = await caches.open(cacheName); sandbox.stub(caches, 'open').resolves(cache); @@ -650,25 +727,35 @@ describe(`StrategyHandler`, function() { await handler.cachePut(initialRequest, response); - expect(spyOne.calledOnceWith(sinon.match({ - mode: 'write', - request: initialRequest, - }))).to.be.true; + expect( + spyOne.calledOnceWith( + sinon.match({ + mode: 'write', + request: initialRequest, + }), + ), + ).to.be.true; expect(spyOne.thisValues[0]).to.eql(firstPlugin); - expect(spyTwo.calledOnceWith(sinon.match({ - mode: 'write', - request: firstPluginReturnValue, - }))).to.be.true; + expect( + spyTwo.calledOnceWith( + sinon.match({ + mode: 'write', + request: firstPluginReturnValue, + }), + ), + ).to.be.true; expect(spyTwo.thisValues[0]).to.eql(secondPlugin); expect(cachePutStub.calledOnce).to.be.true; // Check the url of the Request passed to cache.put(). - expect(cachePutStub.args[0][0].url).to.eql(`${self.location.origin}/secondPlugin`); + expect(cachePutStub.args[0][0].url).to.eql( + `${self.location.origin}/secondPlugin`, + ); expect(cachePutStub.args[0][1]).to.eql(response); }); - it(`should call the quota exceeded callbacks when there's a QuotaExceeded error`, async function() { + it(`should call the quota exceeded callbacks when there's a QuotaExceeded error`, async function () { const callback1 = sandbox.stub(); registerQuotaErrorCallback(callback1); const callback2 = sandbox.stub(); @@ -691,7 +778,7 @@ describe(`StrategyHandler`, function() { expect(callback2.calledOnce).to.be.true; }); - it(`should not call the quota exceeded callbacks when there's a non-QuotaExceeded error`, async function() { + it(`should not call the quota exceeded callbacks when there's a non-QuotaExceeded error`, async function () { const callback = sandbox.stub(); registerQuotaErrorCallback(callback); @@ -714,8 +801,8 @@ describe(`StrategyHandler`, function() { // These tests were copied from `test-cacheWrapper` to ensure we don't // lose any of the existing behavior in the update. - describe(`.cacheMatch()`, function() { - it(`should use the matchOptions that were provided to put()`, async function() { + describe(`.cacheMatch()`, function () { + it(`should use the matchOptions that were provided to put()`, async function () { const matchOptions = { ignoreSearch: true, }; @@ -726,21 +813,27 @@ describe(`StrategyHandler`, function() { const handler = createStrategyHandler({ cacheName, matchOptions, - plugins: [{ - cacheDidUpdate: () => {}, - }], + plugins: [ + { + cacheDidUpdate: () => {}, + }, + ], }); await handler.cacheMatch( - new Request('/test/request'), new Response('test')); + new Request('/test/request'), + new Response('test'), + ); expect(matchSpy.calledOnce).to.be.true; - expect(matchSpy.args[0][1]).to.eql(Object.assign({}, matchOptions, { - cacheName, - })); + expect(matchSpy.args[0][1]).to.eql( + Object.assign({}, matchOptions, { + cacheName, + }), + ); }); - it(`should call cachedResponseWillBeUsed`, async function() { + it(`should call cachedResponseWillBeUsed`, async function () { const options = {}; const matchCacheName = 'MATCH-CACHE-NAME'; const matchRequest = new Request('/test/string'); @@ -765,8 +858,9 @@ describe(`StrategyHandler`, function() { expect(request).to.equal(matchRequest); expect(cacheName).to.equal(matchCacheName); expect(matchOptions).to.equal(options); - expect(cachedResponse.headers.get('x-id')) - .to.equal(matchResponse.headers.get('x-id')); + expect(cachedResponse.headers.get('x-id')).to.equal( + matchResponse.headers.get('x-id'), + ); return firstPluginResponse; }, @@ -782,8 +876,9 @@ describe(`StrategyHandler`, function() { expect(request).to.equal(matchRequest); expect(cacheName).to.equal(matchCacheName); expect(matchOptions).to.equal(options); - expect(cachedResponse.headers.get('x-id')) - .to.equal(firstPluginResponse.headers.get('x-id')); + expect(cachedResponse.headers.get('x-id')).to.equal( + firstPluginResponse.headers.get('x-id'), + ); return secondPluginResponse; }, }; @@ -808,16 +903,18 @@ describe(`StrategyHandler`, function() { const result = await handler.cacheMatch(matchRequest); - expect(result.headers.get('x-id')) - .to.equal(secondPluginResponse.headers.get('x-id')); + expect(result.headers.get('x-id')).to.equal( + secondPluginResponse.headers.get('x-id'), + ); expect(spyOne.callCount).to.equal(1); expect(spyTwo.callCount).to.equal(1); }); - it(`should call cacheKeyWillBeUsed`, async function() { + it(`should call cacheKeyWillBeUsed`, async function () { const cacheName = 'cacheKeyWillBeUsed-test-cache'; - const cacheMatchStub = sandbox.stub(self.caches, 'match').resolves( - new Response('Test response.')); + const cacheMatchStub = sandbox + .stub(self.caches, 'match') + .resolves(new Response('Test response.')); const firstPluginReturnValue = new Request('/firstPlugin'); const firstPlugin = { @@ -846,26 +943,36 @@ describe(`StrategyHandler`, function() { await handler.cacheMatch(initialRequest); - expect(spyOne.calledOnceWith(sinon.match({ - mode: 'read', - request: initialRequest, - }))).to.be.true; + expect( + spyOne.calledOnceWith( + sinon.match({ + mode: 'read', + request: initialRequest, + }), + ), + ).to.be.true; expect(spyOne.thisValues[0]).to.eql(firstPlugin); - expect(spyTwo.calledOnceWith(sinon.match({ - mode: 'read', - request: firstPluginReturnValue, - }))).to.be.true; + expect( + spyTwo.calledOnceWith( + sinon.match({ + mode: 'read', + request: firstPluginReturnValue, + }), + ), + ).to.be.true; expect(spyTwo.thisValues[0]).to.eql(secondPlugin); expect(cacheMatchStub.calledOnce).to.be.true; // Check the url of the Request passed to cache.put(). - expect(cacheMatchStub.args[0][0].url).to.eql(`${self.location.origin}/secondPlugin`); + expect(cacheMatchStub.args[0][0].url).to.eql( + `${self.location.origin}/secondPlugin`, + ); }); }); - describe('fetchAndCachePut()', function() { - it('calls fetch and then cachePut with the response', async function() { + describe('fetchAndCachePut()', function () { + it('calls fetch and then cachePut with the response', async function () { const handler = createStrategyHandler(); sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); @@ -884,7 +991,7 @@ describe(`StrategyHandler`, function() { expect(await spyCall.args[1].text()).to.equal('fetch response'); }); - it(`should work with request string`, async function() { + it(`should work with request string`, async function () { const handler = createStrategyHandler(); sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); @@ -896,7 +1003,7 @@ describe(`StrategyHandler`, function() { expect(self.fetch.args[0][0].url).to.equal(location.origin + '/url'); }); - it(`should work with request object`, async function() { + it(`should work with request object`, async function () { const handler = createStrategyHandler(); sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); @@ -908,7 +1015,7 @@ describe(`StrategyHandler`, function() { expect(self.fetch.args[0][0].url).to.equal(location.origin + '/request'); }); - it(`should keep the handler alive until the cache put settles`, async function() { + it(`should keep the handler alive until the cache put settles`, async function () { const handler = createStrategyHandler(); sandbox.stub(self, 'fetch').resolves(new Response('fetch response')); @@ -918,13 +1025,14 @@ describe(`StrategyHandler`, function() { await handler.fetchAndCachePut('/url'); await handler.doneWaiting(); - expect(handler.waitUntil.calledWith( - handler.cachePut.firstCall.returnValue)).to.be.true; + expect( + handler.waitUntil.calledWith(handler.cachePut.firstCall.returnValue), + ).to.be.true; }); }); - describe('hasCallback()', function() { - it('return true if the strategy contains at least one plugin with the given callback', function() { + describe('hasCallback()', function () { + it('return true if the strategy contains at least one plugin with the given callback', function () { const handler = createStrategyHandler({ plugins: [ { @@ -951,8 +1059,8 @@ describe(`StrategyHandler`, function() { }); }); - describe('runCallbacks()', function() { - it('runs all matching callbacks with the correct arguments', async function() { + describe('runCallbacks()', function () { + it('runs all matching callbacks with the correct arguments', async function () { const spy = sandbox.spy(); const handler = createStrategyHandler({ plugins: [ @@ -984,7 +1092,7 @@ describe(`StrategyHandler`, function() { expect(spy.secondCall.args[0].state).to.be.instanceOf(Object); }); - it('uses a unique state object per plugin', async function() { + it('uses a unique state object per plugin', async function () { const plugins = [ { handlerWillStart: sandbox.spy(), @@ -1011,28 +1119,33 @@ describe(`StrategyHandler`, function() { // All of the `handlerWillStart` callbacks are from different plugins, // so they should all have different state objects. - expect(plugins[0].handlerWillStart.firstCall.args[0].state) - .not.to.equal(plugins[1].handlerWillStart.firstCall.args[0].state); - expect(plugins[1].handlerWillStart.firstCall.args[0].state) - .not.to.equal(plugins[3].handlerWillStart.firstCall.args[0].state); + expect(plugins[0].handlerWillStart.firstCall.args[0].state).not.to.equal( + plugins[1].handlerWillStart.firstCall.args[0].state, + ); + expect(plugins[1].handlerWillStart.firstCall.args[0].state).not.to.equal( + plugins[3].handlerWillStart.firstCall.args[0].state, + ); await handler.runCallbacks('handlerDidComplete', {request, event}); // All of the `handlerDidComplete` callbacks are from different plugins, // so they should also all have different state objects. - expect(plugins[0].handlerDidComplete.firstCall.args[0].state) - .not.to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); + expect( + plugins[0].handlerDidComplete.firstCall.args[0].state, + ).not.to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); // State objects from callbacks in the same plugin should be the same. - expect(plugins[0].handlerWillStart.firstCall.args[0].state) - .to.equal(plugins[0].handlerDidComplete.firstCall.args[0].state); - expect(plugins[3].handlerWillStart.firstCall.args[0].state) - .to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); + expect(plugins[0].handlerWillStart.firstCall.args[0].state).to.equal( + plugins[0].handlerDidComplete.firstCall.args[0].state, + ); + expect(plugins[3].handlerWillStart.firstCall.args[0].state).to.equal( + plugins[3].handlerDidComplete.firstCall.args[0].state, + ); }); }); - describe('iterateCallbacks()', function() { - it('loops through all matching callbacks', async function() { + describe('iterateCallbacks()', function () { + it('loops through all matching callbacks', async function () { const spy = sandbox.spy(); const handler = createStrategyHandler({ plugins: [ @@ -1063,7 +1176,7 @@ describe(`StrategyHandler`, function() { } }); - it('uses a unique state object per plugin', async function() { + it('uses a unique state object per plugin', async function () { const plugins = [ { handlerWillStart: sandbox.spy(), @@ -1092,10 +1205,12 @@ describe(`StrategyHandler`, function() { // All of the `handlerWillStart` callbacks are from different plugins, // so they should all have different state objects. - expect(plugins[0].handlerWillStart.firstCall.args[0].state) - .not.to.equal(plugins[1].handlerWillStart.firstCall.args[0].state); - expect(plugins[1].handlerWillStart.firstCall.args[0].state) - .not.to.equal(plugins[3].handlerWillStart.firstCall.args[0].state); + expect(plugins[0].handlerWillStart.firstCall.args[0].state).not.to.equal( + plugins[1].handlerWillStart.firstCall.args[0].state, + ); + expect(plugins[1].handlerWillStart.firstCall.args[0].state).not.to.equal( + plugins[3].handlerWillStart.firstCall.args[0].state, + ); for (const callback of handler.iterateCallbacks('handlerDidComplete')) { await callback({event, request}); @@ -1103,17 +1218,20 @@ describe(`StrategyHandler`, function() { // All of the `handlerDidComplete` callbacks are from different plugins, // so they should also all have different state objects. - expect(plugins[0].handlerDidComplete.firstCall.args[0].state) - .not.to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); + expect( + plugins[0].handlerDidComplete.firstCall.args[0].state, + ).not.to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); // State objects from callbacks in the same plugin should be the same. - expect(plugins[0].handlerWillStart.firstCall.args[0].state) - .to.equal(plugins[0].handlerDidComplete.firstCall.args[0].state); - expect(plugins[3].handlerWillStart.firstCall.args[0].state) - .to.equal(plugins[3].handlerDidComplete.firstCall.args[0].state); + expect(plugins[0].handlerWillStart.firstCall.args[0].state).to.equal( + plugins[0].handlerDidComplete.firstCall.args[0].state, + ); + expect(plugins[3].handlerWillStart.firstCall.args[0].state).to.equal( + plugins[3].handlerDidComplete.firstCall.args[0].state, + ); }); - it('returns the value returned by the callback', async function() { + it('returns the value returned by the callback', async function () { let request = new Request('/test-request'); const event = new FetchEvent('fetch', {request}); @@ -1143,8 +1261,8 @@ describe(`StrategyHandler`, function() { }); }); - describe(`getCacheKey`, function() { - it(`returns the cackeKey after applying plugins`, async function() { + describe(`getCacheKey`, function () { + it(`returns the cackeKey after applying plugins`, async function () { const request = new Request('/test'); const handler = createStrategyHandler({ plugins: [ @@ -1155,14 +1273,16 @@ describe(`StrategyHandler`, function() { }, { cacheKeyWillBeUsed({mode, request}) { - return mode === 'read' ? - new Request(request.url + '+read') : request; + return mode === 'read' + ? new Request(request.url + '+read') + : request; }, }, { cacheKeyWillBeUsed({mode, request}) { - return mode === 'write' ? - new Request(request.url + '+write') : request; + return mode === 'write' + ? new Request(request.url + '+write') + : request; }, }, ], @@ -1175,7 +1295,7 @@ describe(`StrategyHandler`, function() { expect(writeCacheKey.url).to.equal(location.origin + '/test+1+write'); }); - it(`caches the key per mode to avoid repeat invocations`, async function() { + it(`caches the key per mode to avoid repeat invocations`, async function () { const request = new Request('/test'); const plugin = { cacheKeyWillBeUsed({mode, request}) { diff --git a/test/workbox-strategies/sw/test-UsageWithRouter.mjs b/test/workbox-strategies/sw/test-UsageWithRouter.mjs index 61196ce51..408ce75ea 100644 --- a/test/workbox-strategies/sw/test-UsageWithRouter.mjs +++ b/test/workbox-strategies/sw/test-UsageWithRouter.mjs @@ -13,25 +13,33 @@ import {NetworkOnly} from 'workbox-strategies/NetworkOnly.mjs'; import {StaleWhileRevalidate} from 'workbox-strategies/StaleWhileRevalidate.mjs'; import {Router} from 'workbox-routing/Router.mjs'; import {Route} from 'workbox-routing/Route.mjs'; -import {eventDoneWaiting, spyOnEvent} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; +import { + eventDoneWaiting, + spyOnEvent, +} from '../../../infra/testing/helpers/extendable-event-utils.mjs'; import {generateUniqueResponse} from '../../../infra/testing/helpers/generateUniqueResponse.mjs'; - -describe(`Router`, function() { +describe(`Router`, function () { const sandbox = sinon.createSandbox(); - beforeEach(async function() { + beforeEach(async function () { sandbox.restore(); sandbox.stub(self, 'fetch').resolves(generateUniqueResponse()); sandbox.stub(Cache.prototype, 'match').resolves(generateUniqueResponse()); }); - after(async function() { + after(async function () { sandbox.restore(); }); - [CacheFirst, CacheOnly, NetworkFirst, NetworkOnly, StaleWhileRevalidate].forEach((StrategyClass) => { - it(`should work with the '${StrategyClass.name}' strategy`, async function() { + [ + CacheFirst, + CacheOnly, + NetworkFirst, + NetworkOnly, + StaleWhileRevalidate, + ].forEach((StrategyClass) => { + it(`should work with the '${StrategyClass.name}' strategy`, async function () { const router = new Router(); router.registerRoute(new Route(() => true, new StrategyClass())); diff --git a/test/workbox-streams/integration/test-all.js b/test/workbox-streams/integration/test-all.js index 30671cca6..27ebac634 100644 --- a/test/workbox-streams/integration/test-all.js +++ b/test/workbox-streams/integration/test-all.js @@ -10,40 +10,42 @@ const {expect} = require('chai'); const activateAndControlSW = require('../../../infra/testing/activate-and-control'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-streams]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-streams]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-streams/sw/'); }); }); -describe(`[workbox-streams] Integration Tests`, function() { +describe(`[workbox-streams] Integration Tests`, function () { const testServerAddress = server.getAddress(); const testingURL = `${testServerAddress}/test/workbox-streams/static/`; const swURL = `${testingURL}sw.js`; - before(async function() { + before(async function () { await webdriver.get(testingURL); await activateAndControlSW(swURL); }); for (const testCase of ['concatenate', 'concatenateToResponse', 'strategy']) { - it(`should return the expected response for the '${testCase}' approach`, async function() { - const {text, headers} = await webdriver.executeAsyncScript(async (testCase, cb) => { - try { - const response = await fetch(new URL(testCase, location)); - const headers = [...response.headers].sort((a, b) => { - return a[0] > b[0]; - }); - const text = await response.text(); - cb({headers, text}); - } catch (error) { - cb({text: error.message}); - } - }, testCase); + it(`should return the expected response for the '${testCase}' approach`, async function () { + const {text, headers} = await webdriver.executeAsyncScript( + async (testCase, cb) => { + try { + const response = await fetch(new URL(testCase, location)); + const headers = [...response.headers].sort((a, b) => { + return a[0] > b[0]; + }); + const text = await response.text(); + cb({headers, text}); + } catch (error) { + cb({text: error.message}); + } + }, + testCase, + ); if (text === 'No streams support') { this.skip(); diff --git a/test/workbox-streams/static/sw.js b/test/workbox-streams/static/sw.js index c79b90284..0ced98399 100644 --- a/test/workbox-streams/static/sw.js +++ b/test/workbox-streams/static/sw.js @@ -26,14 +26,19 @@ self.addEventListener('fetch', (event) => { if (!workbox.streams.isSupported()) { event.respondWith(new Response('No streams support')); } else if (event.request.url.endsWith('concatenateToResponse')) { - const {done, response} = workbox.streams.concatenateToResponse(getSourceFunctions().map((f) => f()), { - 'content-type': 'text/plain', - 'x-test-case': 'concatenateToResponse', - }); + const {done, response} = workbox.streams.concatenateToResponse( + getSourceFunctions().map((f) => f()), + { + 'content-type': 'text/plain', + 'x-test-case': 'concatenateToResponse', + }, + ); event.respondWith(response); event.waitUntil(done); } else if (event.request.url.endsWith('concatenate')) { - const {done, stream} = workbox.streams.concatenate(getSourceFunctions().map((f) => f())); + const {done, stream} = workbox.streams.concatenate( + getSourceFunctions().map((f) => f()), + ); const response = new Response(stream, { headers: { 'content-type': 'text/plain', @@ -46,9 +51,9 @@ self.addEventListener('fetch', (event) => { }); workbox.routing.registerRoute( - new RegExp('strategy$'), - workbox.streams.strategy(getSourceFunctions(), { - 'content-type': 'text/plain', - 'x-test-case': 'strategy', - }), + new RegExp('strategy$'), + workbox.streams.strategy(getSourceFunctions(), { + 'content-type': 'text/plain', + 'x-test-case': 'strategy', + }), ); diff --git a/test/workbox-streams/sw/test-isSupported.mjs b/test/workbox-streams/sw/test-isSupported.mjs index 2abb26eb7..935d63db9 100644 --- a/test/workbox-streams/sw/test-isSupported.mjs +++ b/test/workbox-streams/sw/test-isSupported.mjs @@ -8,9 +8,8 @@ import {isSupported} from 'workbox-streams/isSupported.mjs'; - -describe(`isSupported`, function() { - it(`should return true when ReadableStream is available`, async function() { +describe(`isSupported`, function () { + it(`should return true when ReadableStream is available`, async function () { try { new ReadableStream({start() {}}); diff --git a/test/workbox-streams/sw/utils/test-createHeaders.mjs b/test/workbox-streams/sw/utils/test-createHeaders.mjs index 9a9c24ee9..8063d93a4 100644 --- a/test/workbox-streams/sw/utils/test-createHeaders.mjs +++ b/test/workbox-streams/sw/utils/test-createHeaders.mjs @@ -8,21 +8,20 @@ import {createHeaders} from 'workbox-streams/utils/createHeaders.mjs'; - -describe(`createHeaders`, function() { +describe(`createHeaders`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); }); - afterEach(function() { + afterEach(function () { sandbox.restore(); }); const DEFAULT_CONTENT_TYPE = ['content-type', 'text/html']; - it(`should use the default Content-Type, and construct with an empty object, when headersInit is undefined`, function() { + it(`should use the default Content-Type, and construct with an empty object, when headersInit is undefined`, function () { const headersSpy = sandbox.spy(self, 'Headers'); const headers = createHeaders(); expect([...headers]).to.eql([DEFAULT_CONTENT_TYPE]); @@ -31,7 +30,7 @@ describe(`createHeaders`, function() { expect(headersSpy.args[0][0]).to.eql({}); }); - it(`should use the default Content-Type along with custom headersInit values`, function() { + it(`should use the default Content-Type along with custom headersInit values`, function () { const headersInit = { 'x-one': '1', 'x-two': '2', @@ -44,7 +43,7 @@ describe(`createHeaders`, function() { ]); }); - it(`should use a custom Content-Type`, function() { + it(`should use a custom Content-Type`, function () { const headersInit = { 'content-type': 'text/plain', }; diff --git a/test/workbox-sw/integration/test-all.js b/test/workbox-sw/integration/test-all.js index 4af6f7932..5a0271de7 100644 --- a/test/workbox-sw/integration/test-all.js +++ b/test/workbox-sw/integration/test-all.js @@ -9,40 +9,40 @@ const expect = require('chai').expect; const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); - // Store local references of these globals. const {webdriver, server} = global.__workbox; -describe(`[workbox-sw]`, function() { - it(`passes all SW unit tests`, async function() { +describe(`[workbox-sw]`, function () { + it(`passes all SW unit tests`, async function () { await runUnitTests('/test/workbox-sw/sw/'); }); }); -describe(`WorkboxSW interface`, function() { +describe(`WorkboxSW interface`, function () { const wasRegistrationSuccessful = (swFile) => { return webdriver.executeAsyncScript((swFile, cb) => { // Invokes cb() with true when registration succeeds, and false otherwise. - navigator.serviceWorker.register(swFile) - .then(() => cb(true)) - .catch(() => cb(false)); + navigator.serviceWorker + .register(swFile) + .then(() => cb(true)) + .catch(() => cb(false)); }, swFile); }; const testServerAddress = server.getAddress(); const testPageURL = `${testServerAddress}/test/workbox-sw/static/integration/`; - before(async function() { + before(async function () { await webdriver.get(testPageURL); }); - it(`should fail to activate an invalid SW which loads non-existent modules`, async function() { + it(`should fail to activate an invalid SW which loads non-existent modules`, async function () { const invalidSW = 'invalid-sw.js'; const outcome = await wasRegistrationSuccessful(invalidSW); expect(outcome).to.be.false; }); - it(`should be able to activate a SW which loads all valid modules`, async function() { + it(`should be able to activate a SW which loads all valid modules`, async function () { const validSW = 'valid-sw.js'; const outcome = await wasRegistrationSuccessful(validSW); expect(outcome).to.be.true; diff --git a/test/workbox-sw/static/index.html b/test/workbox-sw/static/index.html index 150579df0..efd6a1616 100644 --- a/test/workbox-sw/static/index.html +++ b/test/workbox-sw/static/index.html @@ -10,16 +10,12 @@ - - + + -

    - Testing Loading of Workbox via CDN -

    -

    - This page will register a service worker that uses the Workbox CDN. -

    +

    Testing Loading of Workbox via CDN

    +

    This page will register a service worker that uses the Workbox CDN.

    diff --git a/test/workbox-sw/static/integration/index.html b/test/workbox-sw/static/integration/index.html index 0ea8cb448..337e4146d 100644 --- a/test/workbox-sw/static/integration/index.html +++ b/test/workbox-sw/static/integration/index.html @@ -1,10 +1,9 @@ - - +

    You need to manually register sw.js

    - + diff --git a/test/workbox-sw/static/integration/valid-sw.js b/test/workbox-sw/static/integration/valid-sw.js index af72cbc6d..c9b48ab42 100644 --- a/test/workbox-sw/static/integration/valid-sw.js +++ b/test/workbox-sw/static/integration/valid-sw.js @@ -28,6 +28,8 @@ const namespaces = [ for (const namespace of namespaces) { const module = self.workbox[namespace]; if (!module) { - throw new Error(`$self.workbox.{namespace} did not load the expected interface.`); + throw new Error( + `$self.workbox.{namespace} did not load the expected interface.`, + ); } } diff --git a/test/workbox-sw/static/sw.js b/test/workbox-sw/static/sw.js index 4f9991ace..d95f3516f 100644 --- a/test/workbox-sw/static/sw.js +++ b/test/workbox-sw/static/sw.js @@ -20,7 +20,4 @@ wb.clientsClaim(); wb.core.setLogLevel(self.workbox.core.LOG_LEVELS.debug); -wb.precaching.precache([ - 'example.css', - 'example.js', -]); +wb.precaching.precache(['example.css', 'example.js']); diff --git a/test/workbox-sw/sw/controllers/test-WorkboxSW.mjs b/test/workbox-sw/sw/controllers/test-WorkboxSW.mjs index 9e9ff03f3..d8a8cb2e7 100644 --- a/test/workbox-sw/sw/controllers/test-WorkboxSW.mjs +++ b/test/workbox-sw/sw/controllers/test-WorkboxSW.mjs @@ -9,22 +9,21 @@ import {WorkboxSW} from 'workbox-sw/controllers/WorkboxSW.mjs'; import generateTestVariants from '../../../../infra/testing/generate-variant-tests'; - -describe(`WorkboxSW`, function() { +describe(`WorkboxSW`, function () { const sandbox = sinon.createSandbox(); - beforeEach(function() { + beforeEach(function () { sandbox.restore(); delete self.workbox; }); - after(function() { + after(function () { sandbox.restore(); delete self.workbox; }); - describe(`constructor`, function() { - it(`should construct with expect defaults`, function() { + describe(`constructor`, function () { + it(`should construct with expect defaults`, function () { sandbox.stub(location, 'hostname').value('example.com'); self.workbox = new WorkboxSW(); @@ -35,7 +34,7 @@ describe(`WorkboxSW`, function() { }); }); - it(`should construct debug true when on localhost`, function() { + it(`should construct debug true when on localhost`, function () { sandbox.stub(location, 'hostname').value('localhost'); self.workbox = new WorkboxSW(); @@ -43,31 +42,34 @@ describe(`WorkboxSW`, function() { }); }); - describe(`setConfig`, function() { - it(`should override default config options`, function() { + describe(`setConfig`, function () { + it(`should override default config options`, function () { const cb = () => {}; self.workbox = new WorkboxSW(); self.workbox.setConfig({ debug: true, - modulePathPrefix: 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', + modulePathPrefix: + 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', modulePathCb: cb, }); expect(self.workbox._options).to.deep.equal({ debug: true, - modulePathPrefix: 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', + modulePathPrefix: + 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', modulePathCb: cb, }); }); - it(`should throw when invoking config after loading a module`, function() { + it(`should throw when invoking config after loading a module`, function () { sandbox.stub(self, 'importScripts'); self.workbox = new WorkboxSW(); expect(() => { self.workbox.setConfig({ - modulePathPrefix: 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', + modulePathPrefix: + 'http://custom-cdn.example.com/workbox-modules/v1.0.0/', }); }).not.to.throw(); @@ -75,18 +77,21 @@ describe(`WorkboxSW`, function() { self.workbox.core; expect(importScripts.callCount).to.equal(1); - expect(importScripts.args[0][0]).to.equal(`http://custom-cdn.example.com/workbox-modules/v1.0.0/workbox-core.dev.js`); + expect(importScripts.args[0][0]).to.equal( + `http://custom-cdn.example.com/workbox-modules/v1.0.0/workbox-core.dev.js`, + ); expect(() => { self.workbox.setConfig({ - modulePathPrefix: 'http://custom-cdn.example.com/workbox-modules/v2.0.0/', + modulePathPrefix: + 'http://custom-cdn.example.com/workbox-modules/v2.0.0/', }); }).to.throw(); expect(importScripts.callCount).to.equal(1); }); - it(`should not throw on no config and environment should stay the same`, function() { + it(`should not throw on no config and environment should stay the same`, function () { self.workbox = new WorkboxSW(); const originalOptions = self.workbox._options; @@ -97,8 +102,8 @@ describe(`WorkboxSW`, function() { }); }); - describe(`get`, function() { - it(`should print error message when importScripts fails`, function() { + describe(`get`, function () { + it(`should print error message when importScripts fails`, function () { const errorMessage = 'Injected error.'; sandbox.stub(self, 'importScripts').throws(new Error(errorMessage)); @@ -119,7 +124,7 @@ describe(`WorkboxSW`, function() { } }); - it(`should use modulePathCb to load modules if provided`, function() { + it(`should use modulePathCb to load modules if provided`, function () { sandbox.stub(self, 'importScripts'); const callbackSpy = sandbox.spy((moduleName, debug) => { @@ -137,59 +142,74 @@ describe(`WorkboxSW`, function() { expect(callbackSpy.callCount).to.equal(1); expect(callbackSpy.args[0]).to.deep.equal(['workbox-core', true]); - expect(self.importScripts.args[0]).to.deep.equal(['/custom-path/workbox-core/true']); + expect(self.importScripts.args[0]).to.deep.equal([ + '/custom-path/workbox-core/true', + ]); }); const modulePathVariations = [ { prefix: '/', expectedImport: '/workbox-core.dev.js', - }, { + }, + { prefix: '/custom-path', expectedImport: '/custom-path/workbox-core.dev.js', - }, { + }, + { prefix: '/custom-path/', expectedImport: '/custom-path/workbox-core.dev.js', - }, { + }, + { prefix: 'custom-path/', expectedImport: 'custom-path/workbox-core.dev.js', - }, { + }, + { prefix: 'custom-path', expectedImport: 'custom-path/workbox-core.dev.js', - }, { + }, + { prefix: 'custom-path/with/directories/', expectedImport: 'custom-path/with/directories/workbox-core.dev.js', - }, { + }, + { prefix: 'custom-path/with/directories', expectedImport: 'custom-path/with/directories/workbox-core.dev.js', - }, { + }, + { prefix: '/custom-path/with/directories', expectedImport: '/custom-path/with/directories/workbox-core.dev.js', }, ]; - generateTestVariants(`should import using modulePathPrefix`, modulePathVariations, async function(variant) { - sandbox.stub(self, 'importScripts'); + generateTestVariants( + `should import using modulePathPrefix`, + modulePathVariations, + async function (variant) { + sandbox.stub(self, 'importScripts'); - self.workbox = new WorkboxSW(); + self.workbox = new WorkboxSW(); - self.workbox.setConfig({ - debug: true, - modulePathPrefix: variant.prefix, - }); + self.workbox.setConfig({ + debug: true, + modulePathPrefix: variant.prefix, + }); - // Accessing .core loads workbox-core. - self.workbox.core; + // Accessing .core loads workbox-core. + self.workbox.core; - expect(self.importScripts.args[0]).to.deep.equal([variant.expectedImport]); - }); + expect(self.importScripts.args[0]).to.deep.equal([ + variant.expectedImport, + ]); + }, + ); }); SW_NAMESPACES.forEach((namespace) => { // Don't test workbox-sw, which exports the `workbox` namespace. if (namespace === 'workbox') return; - describe(`get ${namespace}`, function() { - it(`should return ${namespace}`, function() { + describe(`get ${namespace}`, function () { + it(`should return ${namespace}`, function () { const getter = namespace.split('.')[1]; self.workbox = new WorkboxSW(); expect(self.workbox[getter]).to.exist; diff --git a/test/workbox-webpack-plugin/node/dependency-check.js b/test/workbox-webpack-plugin/node/dependency-check.js index 541f3871c..bbab0876d 100644 --- a/test/workbox-webpack-plugin/node/dependency-check.js +++ b/test/workbox-webpack-plugin/node/dependency-check.js @@ -9,37 +9,60 @@ const depcheck = require('depcheck'); const upath = require('upath'); -describe(`[workbox-webpack-plugin] Test Dependencies`, function() { - it(`should have required dependencies`, function() { +describe(`[workbox-webpack-plugin] Test Dependencies`, function () { + it(`should have required dependencies`, function () { return new Promise((resolve, reject) => { - depcheck(upath.join(__dirname, '..', '..', '..', 'packages', 'workbox-webpack-plugin'), { - ignoreDirs: [ - 'test', - 'build', - 'demo', - ], - ignoreMatches: [ - '@babel/runtime', - ], - }, (unusedDeps) => { - if (unusedDeps.dependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.dependencies)}`)); - } + depcheck( + upath.join( + __dirname, + '..', + '..', + '..', + 'packages', + 'workbox-webpack-plugin', + ), + { + ignoreDirs: ['test', 'build', 'demo'], + ignoreMatches: ['@babel/runtime'], + }, + (unusedDeps) => { + if (unusedDeps.dependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.dependencies, + )}`, + ), + ); + } - if (unusedDeps.devDependencies.length > 0) { - return reject(new Error(`Unused dependencies defined in package.json: ${JSON.stringify(unusedDeps.devDependencies)}`)); - } + if (unusedDeps.devDependencies.length > 0) { + return reject( + new Error( + `Unused dependencies defined in package.json: ${JSON.stringify( + unusedDeps.devDependencies, + )}`, + ), + ); + } - if (Object.keys(unusedDeps.missing).length > 0) { - return reject(new Error(`Dependencies missing from package.json: ${JSON.stringify(unusedDeps.missing)}`)); - } + if (Object.keys(unusedDeps.missing).length > 0) { + return reject( + new Error( + `Dependencies missing from package.json: ${JSON.stringify( + unusedDeps.missing, + )}`, + ), + ); + } - resolve(); - }); + resolve(); + }, + ); }); }); - it(`should have no devDependencies`, function() { + it(`should have no devDependencies`, function () { // This test exists because there have been a number of situations where // dependencies have been used from the top level project and NOT from // this module itself. So dependencies are checked above and devDependencies diff --git a/test/workbox-webpack-plugin/node/v4/generate-sw.js b/test/workbox-webpack-plugin/node/v4/generate-sw.js index 0bbcc3911..4b984fc0a 100644 --- a/test/workbox-webpack-plugin/node/v4/generate-sw.js +++ b/test/workbox-webpack-plugin/node/v4/generate-sw.js @@ -18,8 +18,10 @@ try { } const upath = require('upath'); const moduleAlias = require('module-alias'); -moduleAlias.addAlias('html-webpack-plugin', upath.resolve('node_modules', - 'html-webpack-plugin-v4')); +moduleAlias.addAlias( + 'html-webpack-plugin', + upath.resolve('node_modules', 'html-webpack-plugin-v4'), +); moduleAlias.addAlias('webpack', upath.resolve('node_modules', 'webpack-v4')); const CopyWebpackPlugin = require('copy-webpack-plugin'); @@ -34,14 +36,22 @@ const webpack = require('webpack'); const CreateWebpackAssetPlugin = require('./lib/create-webpack-asset-plugin'); const validateServiceWorkerRuntime = require('../../../../infra/testing/validator/service-worker-runtime'); const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check'); -const {GenerateSW} = require('../../../../packages/workbox-webpack-plugin/src/index'); +const { + GenerateSW, +} = require('../../../../packages/workbox-webpack-plugin/src/index'); -describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { +describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function () { const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js'; - const SRC_DIR = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); - - describe(`[workbox-webpack-plugin] Runtime errors`, function() { - it(`should lead to a webpack compilation error when passed invalid config`, function(done) { + const SRC_DIR = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); + + describe(`[workbox-webpack-plugin] Runtime errors`, function () { + it(`should lead to a webpack compilation error when passed invalid config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -77,8 +87,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple chunks`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] Multiple chunks`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -90,9 +100,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -105,17 +113,24 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { expect(files).to.have.length(4); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -126,7 +141,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should work when called with importScriptsViaChunks`, function(done) { + it(`should work when called with importScriptsViaChunks`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -141,10 +156,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }, plugins: [ new GenerateSW({ - importScriptsViaChunks: [ - 'imported', - 'INVALID_CHUNK_NAME', - ], + importScriptsViaChunks: ['imported', 'INVALID_CHUNK_NAME'], }), ], }; @@ -155,7 +167,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { try { const statsJson = stats.toJson('verbose'); expect(webpackError).not.to.exist; - expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be.empty; + expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be + .empty; // There should be a warning logged, due to INVALID_CHUNK_NAME. expect(statsJson.warnings).to.have.length(1); @@ -163,17 +176,25 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { expect(files).to.have.length(8); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { // imported-[chunkhash].js.map should *not* be included. importScripts: [ [/^\.\/workbox-[0-9a-f]{8}$/], [/^imported-[0-9a-f]{20}\.js$/], ], // imported-[chunkhash].js should *not* be included. - precacheAndRoute: [[[{ - revision: null, - url: /^main-[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -184,7 +205,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should work when called with additionalManifestEntries`, function(done) { + it(`should work when called with additionalManifestEntries`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -220,26 +241,36 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { expect(files).to.have.length(4); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: 'one', - }, { - revision: '333', - url: 'three', - }, { - revision: null, - url: 'two', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: 'one', + }, + { + revision: '333', + url: 'three', + }, + { + revision: null, + url: 'two', + }, + ], + {}, + ], + ], }, }); @@ -250,7 +281,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should honor the 'chunks' allowlist config`, function(done) { + it(`should honor the 'chunks' allowlist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -279,18 +310,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -299,7 +339,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function(done) { + it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -332,18 +372,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(4); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'main.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'vendors~main.js', - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'main.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'vendors~main.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -352,7 +401,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should honor the 'excludeChunks' denylist config`, function(done) { + it(`should honor the 'excludeChunks' denylist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -381,18 +430,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -401,7 +459,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function(done) { + it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -431,15 +489,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -449,8 +515,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -462,10 +528,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new HtmlWebpackPlugin(), - new GenerateSW(), - ], + plugins: [new HtmlWebpackPlugin(), new GenerateSW()], }; const compiler = webpack(config); @@ -477,19 +540,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -499,8 +574,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -510,10 +585,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW(), ], }; @@ -528,46 +607,52 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { expect(files).to.have.length(11); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'images/example-jpeg.jpg', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'images/example-jpeg.jpg', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -579,8 +664,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function() { - it(`should exclude .map and manifest.js files by default`, function(done) { + describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function () { + it(`should exclude .map and manifest.js files by default`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -607,19 +692,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(9); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest.json', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'not-ignored.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest.json', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'not-ignored.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -628,7 +725,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should allow developers to override the default exclude filter`, function(done) { + it(`should allow developers to override the default exclude filter`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -654,16 +751,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(6); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js.map', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js.map', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -672,7 +780,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should allow developers to allowlist via include`, function(done) { + it(`should allow developers to allowlist via include`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -682,10 +790,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ include: [/.html$/], }), @@ -701,19 +813,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(11); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -722,7 +846,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should allow developers to combine the include and exclude filters`, function(done) { + it(`should allow developers to combine the include and exclude filters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -732,10 +856,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ include: [/.html$/], exclude: [/index/], @@ -752,16 +880,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(11); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -771,8 +910,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] swDest variations`, function() { - it(`should work when swDest is an absolute path`, function(done) { + describe(`[workbox-webpack-plugin] swDest variations`, function () { + it(`should work when swDest is an absolute path`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -798,13 +937,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -814,8 +963,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function() { - it(`should warn when when passed a non-existent chunk`, function(done) { + describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function () { + it(`should warn when when passed a non-existent chunk`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -848,14 +997,20 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { expect(files).to.have.length(3); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -866,7 +1021,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function(done) { + it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -878,10 +1033,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ // Make this large enough to cache some, but not all, files. maximumFileSizeToCacheInBytes: 14 * 1024, @@ -906,47 +1065,55 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(12); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -956,8 +1123,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Customizing output paths and names`, function() { - it(`should honor publicPath`, function(done) { + describe(`[workbox-webpack-plugin] Customizing output paths and names`, function () { + it(`should honor publicPath`, function (done) { const outputDir = tempy.directory(); const publicPath = '/testing/'; const config = { @@ -970,9 +1137,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -984,15 +1149,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1002,11 +1175,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] WASM Code`, function() { + describe(`[workbox-webpack-plugin] WASM Code`, function () { // See https://github.com/GoogleChrome/workbox/issues/1916 - it(`should support projects that bundle WASM code`, function(done) { + it(`should support projects that bundle WASM code`, function (done) { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'wasm-project'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'wasm-project', + ); const config = { mode: 'production', entry: { @@ -1017,10 +1196,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { globalObject: 'self', path: outputDir, }, - plugins: [ - new WorkerPlugin(), - new GenerateSW(), - ], + plugins: [new WorkerPlugin(), new GenerateSW()], }; const compiler = webpack(config); @@ -1043,8 +1219,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Filesystem options`, function() { - it(`should support using MemoryFS as the outputFileSystem`, function(done) { + describe(`[workbox-webpack-plugin] Filesystem options`, function () { + it(`should support using MemoryFS as the outputFileSystem`, function (done) { const memoryFS = new MemoryFS(); const outputDir = '/output/dir'; memoryFS.mkdirpSync(outputDir); @@ -1058,9 +1234,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -1073,15 +1247,28 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = memoryFS.readdirSync(outputDir); expect(files).to.have.length(3); - const swString = memoryFS.readFileSync(`${outputDir}/service-worker.js`, 'utf-8'); + const swString = memoryFS.readFileSync( + `${outputDir}/service-worker.js`, + 'utf-8', + ); - await validateServiceWorkerRuntime({swString, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swString, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1091,11 +1278,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function() { + describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function () { // See https://github.com/GoogleChrome/workbox/issues/2158 - it(`should support multiple compilations using the same plugin instance`, async function() { + it(`should support multiple compilations using the same plugin instance`, async function () { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const config = { mode: 'production', entry: { @@ -1105,9 +1298,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { filename: '[name].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -1142,9 +1333,15 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { } }); - it(`should not list the swDest from one plugin in the other's manifest`, function(done) { + it(`should not list the swDest from one plugin in the other's manifest`, function (done) { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const config = { mode: 'production', entry: { @@ -1179,10 +1376,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { swFile: sw1File, expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.js', + }, + ], + {}, + ], + ], }, }); @@ -1190,10 +1394,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { swFile: sw2File, expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.js', + }, + ], + {}, + ], + ], }, }); @@ -1205,8 +1416,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Rollup plugin configuration options`, function() { - it(`should support inlining the Workbox runtime`, function(done) { + describe(`[workbox-webpack-plugin] Rollup plugin configuration options`, function () { + it(`should support inlining the Workbox runtime`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1241,7 +1452,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should support inlining the Workbox runtime and generating sourcemaps`, function(done) { + it(`should support inlining the Workbox runtime and generating sourcemaps`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1277,7 +1488,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should support using a swDest that includes a subdirectory`, function(done) { + it(`should support using a swDest that includes a subdirectory`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1312,8 +1523,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest transformations`, function() { - it(`should use dontCacheBustURLsMatching`, function(done) { + describe(`[workbox-webpack-plugin] Manifest transformations`, function () { + it(`should use dontCacheBustURLsMatching`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1338,13 +1549,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: /^main\.[0-9a-f]{20}\.js$/, - revision: null, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: /^main\.[0-9a-f]{20}\.js$/, + revision: null, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1353,7 +1574,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should use modifyURLPrefix`, function(done) { + it(`should use modifyURLPrefix`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1381,13 +1602,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1396,7 +1627,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }); }); - it(`should use manifestTransforms`, function(done) { + it(`should use manifestTransforms`, function (done) { const outputDir = tempy.directory(); const warningMessage = 'test warning'; const config = { @@ -1408,24 +1639,26 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { }, plugins: [ new GenerateSW({ - manifestTransforms: [(manifest, compilation) => { - expect(manifest).to.have.lengthOf(1); - expect(manifest[0].size).to.eql(959); - expect(manifest[0].url.startsWith('main.')).to.be.true; - expect(manifest[0].revision).to.be.null; - expect(compilation).to.exist; - - manifest = manifest.map((entry) => { - entry.url += '-suffix'; - entry.revision = null; - return entry; - }); - - return { - manifest, - warnings: [warningMessage], - }; - }], + manifestTransforms: [ + (manifest, compilation) => { + expect(manifest).to.have.lengthOf(1); + expect(manifest[0].size).to.eql(959); + expect(manifest[0].url.startsWith('main.')).to.be.true; + expect(manifest[0].revision).to.be.null; + expect(compilation).to.exist; + + manifest = manifest.map((entry) => { + entry.url += '-suffix'; + entry.revision = null; + return entry; + }); + + return { + manifest, + warnings: [warningMessage], + }; + }, + ], }), ], }; @@ -1436,19 +1669,30 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v4`, function() { try { expect(webpackError).not.to.exist; const statsJson = stats.toJson(); - expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be.empty; + expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be + .empty; expect(statsJson.warnings).to.have.members([warningMessage]); const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js-suffix$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js-suffix$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { diff --git a/test/workbox-webpack-plugin/node/v4/inject-manifest.js b/test/workbox-webpack-plugin/node/v4/inject-manifest.js index 5def25d05..282bf9332 100644 --- a/test/workbox-webpack-plugin/node/v4/inject-manifest.js +++ b/test/workbox-webpack-plugin/node/v4/inject-manifest.js @@ -18,8 +18,10 @@ try { } const upath = require('upath'); const moduleAlias = require('module-alias'); -moduleAlias.addAlias('html-webpack-plugin', upath.resolve('node_modules', - 'html-webpack-plugin-v4')); +moduleAlias.addAlias( + 'html-webpack-plugin', + upath.resolve('node_modules', 'html-webpack-plugin-v4'), +); moduleAlias.addAlias('webpack', upath.resolve('node_modules', 'webpack-v4')); const chai = require('chai'); @@ -35,18 +37,26 @@ const WorkerPlugin = require('worker-plugin'); const CreateWebpackAssetPlugin = require('./lib/create-webpack-asset-plugin'); const validateServiceWorkerRuntime = require('../../../../infra/testing/validator/service-worker-runtime'); const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check'); -const {InjectManifest} = require('../../../../packages/workbox-webpack-plugin/src/index'); +const { + InjectManifest, +} = require('../../../../packages/workbox-webpack-plugin/src/index'); chai.use(chaiMatchPattern); const {expect} = chai; -describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { +describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function () { const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js'; - const SRC_DIR = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const SRC_DIR = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const SW_SRC = upath.join(__dirname, '..', '..', 'static', 'sw-src.js'); - describe(`[workbox-webpack-plugin] Runtime errors`, function() { - it(`should lead to a webpack compilation error when passed invalid config`, function(done) { + describe(`[workbox-webpack-plugin] Runtime errors`, function () { + it(`should lead to a webpack compilation error when passed invalid config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -82,7 +92,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should lead to a webpack compilation error when the swSrc contains multiple injection points`, function(done) { + it(`should lead to a webpack compilation error when the swSrc contains multiple injection points`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -95,7 +105,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'bad-multiple-injection.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'bad-multiple-injection.js', + ), }), ], }; @@ -118,8 +134,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple chunks`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] Multiple chunks`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -152,15 +168,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -171,7 +193,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should honor the 'chunks' allowlist config`, function(done) { + it(`should honor the 'chunks' allowlist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -206,15 +228,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -225,7 +253,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function(done) { + it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -264,15 +292,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'main.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'vendors~main.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'main.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'vendors~main.js', + }, + ], + {}, + ], + ], }, }); @@ -283,7 +317,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should honor the 'excludeChunks' denylist config`, function(done) { + it(`should honor the 'excludeChunks' denylist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -318,15 +352,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -337,7 +377,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function(done) { + it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -373,12 +413,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -390,8 +435,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -425,16 +470,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + ], + {}, + ], + ], }, }); @@ -446,8 +500,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -457,10 +511,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -481,44 +539,49 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'images/example-jpeg.jpg', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'images/example-jpeg.jpg', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -530,8 +593,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function() { - it(`should update the sourcemap to account for manifest injection`, function(done) { + describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function () { + it(`should update the sourcemap to account for manifest injection`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -559,8 +622,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { expect(files).to.have.length(4); const expectedSourcemap = await fse.readJSON( - upath.join(__dirname, '..', '..', 'static', 'expected-service-worker.js.map')); - const actualSourcemap = await fse.readJSON(upath.join(outputDir, 'service-worker.js.map')); + upath.join( + __dirname, + '..', + '..', + 'static', + 'expected-service-worker.js.map', + ), + ); + const actualSourcemap = await fse.readJSON( + upath.join(outputDir, 'service-worker.js.map'), + ); // The mappings will vary depending on the webpack version. delete expectedSourcemap.mappings; @@ -572,10 +644,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -586,7 +665,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should handle a custom output.sourceMapFilename`, function(done) { + it(`should handle a custom output.sourceMapFilename`, function (done) { const outputDir = tempy.directory(); const sourceMapFilename = upath.join('subdir', '[file].map'); @@ -617,9 +696,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { expect(files).to.have.length(4); const expectedSourcemap = await fse.readJSON( - upath.join(__dirname, '..', '..', 'static', 'expected-service-worker.js.map')); + upath.join( + __dirname, + '..', + '..', + 'static', + 'expected-service-worker.js.map', + ), + ); const actualSourcemap = await fse.readJSON( - upath.join(outputDir, 'subdir', 'service-worker.js.map')); + upath.join(outputDir, 'subdir', 'service-worker.js.map'), + ); // The mappings will vary depending on the webpack version. delete expectedSourcemap.mappings; @@ -631,10 +718,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -645,9 +739,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should not fail if the sourcemap is missing from the assets`, function(done) { + it(`should not fail if the sourcemap is missing from the assets`, function (done) { const outputDir = tempy.directory(); - const swSrc = upath.join(__dirname, '..', '..', 'static', 'sw-src-missing-sourcemap.js'); + const swSrc = upath.join( + __dirname, + '..', + '..', + 'static', + 'sw-src-missing-sourcemap.js', + ); const config = { mode: 'development', @@ -678,10 +778,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -693,7 +800,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); // See https://github.com/GoogleChrome/workbox/issues/2729 - it(`should produce valid JavaScript when eval-cheap-source-map and minimization are used`, function(done) { + it(`should produce valid JavaScript when eval-cheap-source-map and minimization are used`, function (done) { const outputDir = tempy.directory(); const config = { @@ -709,7 +816,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'module-import-sw.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'module-import-sw.js', + ), swDest: 'service-worker.js', }), ], @@ -740,7 +853,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); // See https://github.com/GoogleChrome/workbox/issues/2729 - it(`should produce valid JavaScript when eval-cheap-source-map is used without minimization`, function(done) { + it(`should produce valid JavaScript when eval-cheap-source-map is used without minimization`, function (done) { const outputDir = tempy.directory(); const config = { @@ -756,7 +869,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'module-import-sw.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'module-import-sw.js', + ), swDest: 'service-worker.js', }), ], @@ -787,8 +906,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function() { - it(`should exclude .map and manifest.js files by default`, function(done) { + describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function () { + it(`should exclude .map and manifest.js files by default`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -822,16 +941,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest.json', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'not-ignored.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest.json', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'not-ignored.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -842,7 +970,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should allow developers to override the default exclude filter`, function(done) { + it(`should allow developers to override the default exclude filter`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -874,13 +1002,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js.map', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js.map', + }, + ], + {}, + ], + ], }, }); @@ -891,7 +1027,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should allow developers to allowlist via include`, function(done) { + it(`should allow developers to allowlist via include`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -901,10 +1037,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -926,16 +1066,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], }, }); @@ -946,7 +1095,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should allow developers to combine the include and exclude filters`, function(done) { + it(`should allow developers to combine the include and exclude filters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -956,10 +1105,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -982,13 +1135,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], }, }); @@ -1000,8 +1161,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] swDest variations`, function() { - it(`should work when swDest is an absolute path`, function(done) { + describe(`[workbox-webpack-plugin] swDest variations`, function () { + it(`should work when swDest is an absolute path`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1031,10 +1192,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -1046,8 +1214,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function() { - it(`should warn when when passed a non-existent chunk`, function(done) { + describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function () { + it(`should warn when when passed a non-existent chunk`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1085,12 +1253,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1101,7 +1274,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function(done) { + it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1113,10 +1286,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -1147,44 +1324,49 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -1196,8 +1378,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Customizing output paths and names`, function() { - it(`should honor publicPath`, function(done) { + describe(`[workbox-webpack-plugin] Customizing output paths and names`, function () { + it(`should honor publicPath`, function (done) { const outputDir = tempy.directory(); const publicPath = '/testing/'; const config = { @@ -1231,12 +1413,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1248,11 +1435,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] WASM Code`, function() { + describe(`[workbox-webpack-plugin] WASM Code`, function () { // See https://github.com/GoogleChrome/workbox/issues/1916 - it(`should support projects that bundle WASM code`, function(done) { + it(`should support projects that bundle WASM code`, function (done) { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'wasm-project'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'wasm-project', + ); const config = { mode: 'production', entry: { @@ -1292,8 +1485,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest transformations`, function() { - it(`should use dontCacheBustURLsMatching`, function(done) { + describe(`[workbox-webpack-plugin] Manifest transformations`, function () { + it(`should use dontCacheBustURLsMatching`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1324,10 +1517,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - url: /^main\.[0-9a-f]{20}\.js$/, - revision: null, - }], {}]], + precacheAndRoute: [ + [ + [ + { + url: /^main\.[0-9a-f]{20}\.js$/, + revision: null, + }, + ], + {}, + ], + ], }, }); @@ -1338,7 +1538,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should use modifyURLPrefix`, function(done) { + it(`should use modifyURLPrefix`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1372,10 +1572,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, + }, + ], + {}, + ], + ], }, }); @@ -1386,9 +1593,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should use webpackCompilationPlugins with DefinePlugin`, function(done) { + it(`should use webpackCompilationPlugins with DefinePlugin`, function (done) { const prefix = 'replaced-by-define-plugin'; - const swSrc = upath.join(__dirname, '..', '..', 'static', 'sw-src-define-plugin.js'); + const swSrc = upath.join( + __dirname, + '..', + '..', + 'static', + 'sw-src-define-plugin.js', + ); const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1423,10 +1636,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { entryPoint: 'injectManifest', expectedMethodCalls: { setCacheNameDetails: [[{prefix}]], - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1437,7 +1657,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should use manifestTransforms`, function(done) { + it(`should use manifestTransforms`, function (done) { const outputDir = tempy.directory(); const warningMessage = 'test warning'; const config = { @@ -1451,24 +1671,26 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', - manifestTransforms: [(manifest, compilation) => { - expect(manifest).to.have.lengthOf(1); - expect(manifest[0].size).to.eql(959); - expect(manifest[0].url.startsWith('main.')).to.be.true; - expect(manifest[0].revision).to.be.null; - expect(compilation).to.exist; - - manifest = manifest.map((entry) => { - entry.url += '-suffix'; - entry.revision = null; - return entry; - }); - - return { - manifest, - warnings: [warningMessage], - }; - }], + manifestTransforms: [ + (manifest, compilation) => { + expect(manifest).to.have.lengthOf(1); + expect(manifest[0].size).to.eql(959); + expect(manifest[0].url.startsWith('main.')).to.be.true; + expect(manifest[0].revision).to.be.null; + expect(compilation).to.exist; + + manifest = manifest.map((entry) => { + entry.url += '-suffix'; + entry.revision = null; + return entry; + }); + + return { + manifest, + warnings: [warningMessage], + }; + }, + ], }), ], }; @@ -1489,10 +1711,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main.[0-9a-f]{20}\.js-suffix$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main.[0-9a-f]{20}\.js-suffix$/, + }, + ], + {}, + ], + ], }, }); @@ -1504,8 +1733,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] TypeScript compilation`, function() { - it(`should rename a swSrc with a .ts extension to .js`, function(done) { + describe(`[workbox-webpack-plugin] TypeScript compilation`, function () { + it(`should rename a swSrc with a .ts extension to .js`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1537,9 +1766,9 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function() { + describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function () { // See https://github.com/GoogleChrome/workbox/issues/2158 - it(`should support multiple compilations using the same plugin instance`, async function() { + it(`should support multiple compilations using the same plugin instance`, async function () { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1588,7 +1817,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { } }); - it(`should only log once per invocation when using multiple plugin instances`, async function() { + it(`should only log once per invocation when using multiple plugin instances`, async function () { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1642,9 +1871,9 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple plugin instances`, function() { + describe(`[workbox-webpack-plugin] Multiple plugin instances`, function () { // See https://github.com/GoogleChrome/workbox/issues/2181 - it(`should not list the swDest from one plugin in the other's manifest`, function(done) { + it(`should not list the swDest from one plugin in the other's manifest`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1682,10 +1911,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile: sw1File, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1693,10 +1929,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile: sw2File, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1708,8 +1951,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest injection in development mode`, function() { - it(`should produce valid, parsable JavaScript`, function(done) { + describe(`[workbox-webpack-plugin] Manifest injection in development mode`, function () { + it(`should produce valid, parsable JavaScript`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'development', @@ -1741,10 +1984,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { swFile: swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1756,8 +2006,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - describe(`[workbox-webpack-plugin] Non-compilation scenarios`, function() { - it(`should warn when compileSrc is false and webpackCompilationPlugins is used`, function(done) { + describe(`[workbox-webpack-plugin] Non-compilation scenarios`, function () { + it(`should warn when compileSrc is false and webpackCompilationPlugins is used`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1771,7 +2021,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.json', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.json'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.json', + ), webpackCompilationPlugins: [{}], }), ], @@ -1793,7 +2049,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should support injecting a manifest into a JSON file`, function(done) { + it(`should support injecting a manifest into a JSON file`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1807,7 +2063,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.json', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.json'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.json', + ), }), ], }; @@ -1820,11 +2082,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(2); - const manifest = await fse.readJSON(upath.join(outputDir, 'injected-manifest.json')); - expect(manifest).to.matchPattern([{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }]); + const manifest = await fse.readJSON( + upath.join(outputDir, 'injected-manifest.json'), + ); + expect(manifest).to.matchPattern([ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ]); done(); } catch (error) { @@ -1833,7 +2099,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { }); }); - it(`should support injecting a manifest into a CJS module`, function(done) { + it(`should support injecting a manifest into a CJS module`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1847,7 +2113,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.js', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.js', + ), }), ], }; @@ -1860,11 +2132,16 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v4`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(2); - const manifest = require(upath.join(outputDir, 'injected-manifest.js')); - expect(manifest).to.matchPattern([{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }]); + const manifest = require(upath.join( + outputDir, + 'injected-manifest.js', + )); + expect(manifest).to.matchPattern([ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ]); done(); } catch (error) { diff --git a/test/workbox-webpack-plugin/node/v4/lib/create-webpack-asset-plugin.js b/test/workbox-webpack-plugin/node/v4/lib/create-webpack-asset-plugin.js index 35bbb5370..f2be51ee1 100644 --- a/test/workbox-webpack-plugin/node/v4/lib/create-webpack-asset-plugin.js +++ b/test/workbox-webpack-plugin/node/v4/lib/create-webpack-asset-plugin.js @@ -20,11 +20,12 @@ class CreateWebpackAssetPlugin { apply(compiler) { compiler.hooks.emit.tap( - this.constructor.name, - (compilation) => compilation.assets[this.name] = { + this.constructor.name, + (compilation) => + (compilation.assets[this.name] = { source: () => this.name, size: () => this.name.length, - }, + }), ); } } diff --git a/test/workbox-webpack-plugin/node/v5/generate-sw.js b/test/workbox-webpack-plugin/node/v5/generate-sw.js index c46b469ae..f5178052c 100644 --- a/test/workbox-webpack-plugin/node/v5/generate-sw.js +++ b/test/workbox-webpack-plugin/node/v5/generate-sw.js @@ -18,8 +18,10 @@ try { } const upath = require('upath'); const moduleAlias = require('module-alias'); -moduleAlias.addAlias('html-webpack-plugin', upath.resolve('node_modules', - 'html-webpack-plugin-v5')); +moduleAlias.addAlias( + 'html-webpack-plugin', + upath.resolve('node_modules', 'html-webpack-plugin-v5'), +); moduleAlias.addAlias('webpack', upath.resolve('node_modules', 'webpack-v5')); const CopyWebpackPlugin = require('copy-webpack-plugin'); @@ -33,14 +35,22 @@ const webpack = require('webpack'); const CreateWebpackAssetPlugin = require('./lib/create-webpack-asset-plugin'); const validateServiceWorkerRuntime = require('../../../../infra/testing/validator/service-worker-runtime'); const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check'); -const {GenerateSW} = require('../../../../packages/workbox-webpack-plugin/src/index'); +const { + GenerateSW, +} = require('../../../../packages/workbox-webpack-plugin/src/index'); -describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { +describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function () { const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js'; - const SRC_DIR = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); - - describe(`[workbox-webpack-plugin] Runtime errors`, function() { - it(`should lead to a webpack compilation error when passed invalid config`, function(done) { + const SRC_DIR = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); + + describe(`[workbox-webpack-plugin] Runtime errors`, function () { + it(`should lead to a webpack compilation error when passed invalid config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -66,7 +76,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { expect(statsJson.warnings).to.be.empty; expect(statsJson.errors).to.have.length(1); expect(statsJson.errors[0].message).to.eql( - `Please check your GenerateSW plugin configuration:\n[WebpackGenerateSW] 'invalid' property is not expected to be here. Did you mean property 'include'?`, + `Please check your GenerateSW plugin configuration:\n[WebpackGenerateSW] 'invalid' property is not expected to be here. Did you mean property 'include'?`, ); done(); @@ -77,8 +87,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple chunks`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] Multiple chunks`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -90,9 +100,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -105,17 +113,24 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { expect(files).to.have.length(4); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -126,7 +141,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should work when called with importScriptsViaChunks`, function(done) { + it(`should work when called with importScriptsViaChunks`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -141,10 +156,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }, plugins: [ new GenerateSW({ - importScriptsViaChunks: [ - 'imported', - 'INVALID_CHUNK_NAME', - ], + importScriptsViaChunks: ['imported', 'INVALID_CHUNK_NAME'], }), ], }; @@ -163,17 +175,25 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { expect(files).to.have.length(8); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { // imported-[chunkhash].js.map should *not* be included. importScripts: [ [/^\.\/workbox-[0-9a-f]{8}$/], [/^imported-[0-9a-f]{20}\.js$/], ], // imported-[chunkhash].js should *not* be included. - precacheAndRoute: [[[{ - revision: null, - url: /^main-[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -184,7 +204,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should work when called with additionalManifestEntries`, function(done) { + it(`should work when called with additionalManifestEntries`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -220,26 +240,36 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { expect(files).to.have.length(4); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: 'one', - }, { - revision: '333', - url: 'three', - }, { - revision: null, - url: 'two', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: 'one', + }, + { + revision: '333', + url: 'three', + }, + { + revision: null, + url: 'two', + }, + ], + {}, + ], + ], }, }); @@ -250,7 +280,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should honor the 'chunks' allowlist config`, function(done) { + it(`should honor the 'chunks' allowlist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -279,18 +309,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -299,7 +338,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function(done) { + it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -335,18 +374,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(4); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -355,7 +403,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should honor the 'excludeChunks' denylist config`, function(done) { + it(`should honor the 'excludeChunks' denylist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -384,18 +432,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -404,7 +461,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function(done) { + it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -434,15 +491,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -452,8 +517,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -465,10 +530,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new HtmlWebpackPlugin(), - new GenerateSW(), - ], + plugins: [new HtmlWebpackPlugin(), new GenerateSW()], }; const compiler = webpack(config); @@ -480,19 +542,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(5); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -502,8 +576,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -513,10 +587,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW(), ], }; @@ -531,46 +609,52 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { expect(files).to.have.length(11); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'images/example-jpeg.jpg', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'images/example-jpeg.jpg', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -582,8 +666,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function() { - it(`should exclude .map and manifest.js files by default`, function(done) { + describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function () { + it(`should exclude .map and manifest.js files by default`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -610,19 +694,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(9); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest.json', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'not-ignored.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest.json', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'not-ignored.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -631,7 +727,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should allow developers to override the default exclude filter`, function(done) { + it(`should allow developers to override the default exclude filter`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -656,13 +752,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest-normally-ignored.js', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest-normally-ignored.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -671,7 +777,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should allow developers to allowlist via include`, function(done) { + it(`should allow developers to allowlist via include`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -681,10 +787,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ include: [/.html$/], }), @@ -700,19 +810,31 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(11); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -721,7 +843,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should allow developers to combine the include and exclude filters`, function(done) { + it(`should allow developers to combine the include and exclude filters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -731,10 +853,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ include: [/.html$/], exclude: [/index/], @@ -751,16 +877,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(11); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -770,8 +907,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] swDest variations`, function() { - it(`should work when swDest is an absolute path`, function(done) { + describe(`[workbox-webpack-plugin] swDest variations`, function () { + it(`should work when swDest is an absolute path`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -797,13 +934,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -813,8 +960,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function() { - it(`should warn when when passed a non-existent chunk`, function(done) { + describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function () { + it(`should warn when when passed a non-existent chunk`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -840,21 +987,27 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const statsJson = stats.toJson(); expect(statsJson.errors).to.be.empty; expect(statsJson.warnings[0].message).to.eql( - `The chunk 'doesNotExist' was provided in your Workbox chunks config, but was not found in the compilation.`, + `The chunk 'doesNotExist' was provided in your Workbox chunks config, but was not found in the compilation.`, ); const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); await validateServiceWorkerRuntime({ - swFile, expectedMethodCalls: { + swFile, + expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -865,7 +1018,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function(done) { + it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -877,10 +1030,14 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new GenerateSW({ // Make this large enough to cache some, but not all, files. maximumFileSizeToCacheInBytes: 14 * 1024, @@ -897,7 +1054,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { try { const statsJson = stats.toJson('verbose'); expect(statsJson.warnings[0].message).to.eql( - `images/example-jpeg.jpg is 15.3 kB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.`, + `images/example-jpeg.jpg is 15.3 kB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.`, ); const swFile = upath.join(outputDir, 'service-worker.js'); @@ -905,47 +1062,55 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(12); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -955,8 +1120,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Customizing output paths and names`, function() { - it(`should honor publicPath`, function(done) { + describe(`[workbox-webpack-plugin] Customizing output paths and names`, function () { + it(`should honor publicPath`, function (done) { const outputDir = tempy.directory(); const publicPath = '/testing/'; const config = { @@ -969,9 +1134,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -983,15 +1146,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[ - { - revision: null, - url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1001,8 +1172,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Filesystem options`, function() { - it(`should support using MemoryFS as the outputFileSystem`, function(done) { + describe(`[workbox-webpack-plugin] Filesystem options`, function () { + it(`should support using MemoryFS as the outputFileSystem`, function (done) { const memoryFS = new MemoryFS(); const outputDir = '/output/dir'; memoryFS.mkdirpSync(outputDir); @@ -1016,9 +1187,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { filename: '[name]-[chunkhash].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -1031,15 +1200,28 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = memoryFS.readdirSync(outputDir); expect(files).to.have.length(3); - const swString = memoryFS.readFileSync(`${outputDir}/service-worker.js`, 'utf-8'); + const swString = memoryFS.readFileSync( + `${outputDir}/service-worker.js`, + 'utf-8', + ); - await validateServiceWorkerRuntime({swString, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swString, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1049,11 +1231,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function() { + describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function () { // See https://github.com/GoogleChrome/workbox/issues/2158 - it(`should support multiple compilations using the same plugin instance`, async function() { + it(`should support multiple compilations using the same plugin instance`, async function () { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const config = { mode: 'production', entry: { @@ -1063,9 +1251,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { filename: '[name].js', path: outputDir, }, - plugins: [ - new GenerateSW(), - ], + plugins: [new GenerateSW()], }; const compiler = webpack(config); @@ -1100,9 +1286,15 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { } }); - it(`should not list the swDest from one plugin in the other's manifest`, function(done) { + it(`should not list the swDest from one plugin in the other's manifest`, function (done) { const outputDir = tempy.directory(); - const srcDir = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const srcDir = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const config = { mode: 'production', entry: { @@ -1137,10 +1329,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { swFile: sw1File, expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.js', + }, + ], + {}, + ], + ], }, }); @@ -1148,10 +1347,17 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { swFile: sw2File, expectedMethodCalls: { importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.js', + }, + ], + {}, + ], + ], }, }); @@ -1163,8 +1369,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Rollup plugin configuration options`, function() { - it(`should support inlining the Workbox runtime`, function(done) { + describe(`[workbox-webpack-plugin] Rollup plugin configuration options`, function () { + it(`should support inlining the Workbox runtime`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1199,7 +1405,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should support inlining the Workbox runtime and generating sourcemaps`, function(done) { + it(`should support inlining the Workbox runtime and generating sourcemaps`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1235,7 +1441,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should support using a swDest that includes a subdirectory`, function(done) { + it(`should support using a swDest that includes a subdirectory`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1270,8 +1476,8 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest transformations`, function() { - it(`should use dontCacheBustURLsMatching`, function(done) { + describe(`[workbox-webpack-plugin] Manifest transformations`, function () { + it(`should use dontCacheBustURLsMatching`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1296,13 +1502,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - url: /^main\.[0-9a-f]{20}\.js$/, - revision: null, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + url: /^main\.[0-9a-f]{20}\.js$/, + revision: null, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1311,7 +1527,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should use modifyURLPrefix`, function(done) { + it(`should use modifyURLPrefix`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1339,13 +1555,23 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { @@ -1354,7 +1580,7 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }); }); - it(`should use manifestTransforms`, function(done) { + it(`should use manifestTransforms`, function (done) { const outputDir = tempy.directory(); const warningMessage = 'test warning'; const config = { @@ -1366,24 +1592,26 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { }, plugins: [ new GenerateSW({ - manifestTransforms: [(manifest, compilation) => { - expect(manifest).to.have.lengthOf(1); - expect(manifest[0].size).to.eql(30); - expect(manifest[0].url.startsWith('main.')).to.be.true; - expect(manifest[0].revision).to.be.null; - expect(compilation).to.exist; - - manifest = manifest.map((entry) => { - entry.url += '-suffix'; - entry.revision = null; - return entry; - }); - - return { - manifest, - warnings: [warningMessage], - }; - }], + manifestTransforms: [ + (manifest, compilation) => { + expect(manifest).to.have.lengthOf(1); + expect(manifest[0].size).to.eql(30); + expect(manifest[0].url.startsWith('main.')).to.be.true; + expect(manifest[0].revision).to.be.null; + expect(compilation).to.exist; + + manifest = manifest.map((entry) => { + entry.url += '-suffix'; + entry.revision = null; + return entry; + }); + + return { + manifest, + warnings: [warningMessage], + }; + }, + ], }), ], }; @@ -1394,19 +1622,30 @@ describe(`[workbox-webpack-plugin] GenerateSW with webpack v5`, function() { try { expect(webpackError).not.to.exist; const statsJson = stats.toJson(); - expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be.empty; + expect(statsJson.errors, JSON.stringify(statsJson.errors)).to.be + .empty; expect(statsJson.warnings[0].message).to.eql(warningMessage); const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(3); - await validateServiceWorkerRuntime({swFile, expectedMethodCalls: { - importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js-suffix$/, - }], {}]], - }}); + await validateServiceWorkerRuntime({ + swFile, + expectedMethodCalls: { + importScripts: [[/^\.\/workbox-[0-9a-f]{8}$/]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js-suffix$/, + }, + ], + {}, + ], + ], + }, + }); done(); } catch (error) { diff --git a/test/workbox-webpack-plugin/node/v5/inject-manifest.js b/test/workbox-webpack-plugin/node/v5/inject-manifest.js index 68484cbbd..07a481fb6 100644 --- a/test/workbox-webpack-plugin/node/v5/inject-manifest.js +++ b/test/workbox-webpack-plugin/node/v5/inject-manifest.js @@ -18,8 +18,10 @@ try { } const upath = require('upath'); const moduleAlias = require('module-alias'); -moduleAlias.addAlias('html-webpack-plugin', upath.resolve('node_modules', - 'html-webpack-plugin-v5')); +moduleAlias.addAlias( + 'html-webpack-plugin', + upath.resolve('node_modules', 'html-webpack-plugin-v5'), +); moduleAlias.addAlias('webpack', upath.resolve('node_modules', 'webpack-v5')); const chai = require('chai'); @@ -34,18 +36,26 @@ const webpack = require('webpack'); const CreateWebpackAssetPlugin = require('./lib/create-webpack-asset-plugin'); const validateServiceWorkerRuntime = require('../../../../infra/testing/validator/service-worker-runtime'); const webpackBuildCheck = require('../../../../infra/testing/webpack-build-check'); -const {InjectManifest} = require('../../../../packages/workbox-webpack-plugin/src/index'); +const { + InjectManifest, +} = require('../../../../packages/workbox-webpack-plugin/src/index'); chai.use(chaiMatchPattern); const {expect} = chai; -describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { +describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function () { const WEBPACK_ENTRY_FILENAME = 'webpackEntry.js'; - const SRC_DIR = upath.join(__dirname, '..', '..', 'static', 'example-project-1'); + const SRC_DIR = upath.join( + __dirname, + '..', + '..', + 'static', + 'example-project-1', + ); const SW_SRC = upath.join(__dirname, '..', '..', 'static', 'sw-src.js'); - describe(`[workbox-webpack-plugin] Runtime errors`, function() { - it(`should lead to a webpack compilation error when passed invalid config`, function(done) { + describe(`[workbox-webpack-plugin] Runtime errors`, function () { + it(`should lead to a webpack compilation error when passed invalid config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -71,7 +81,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const statsJson = stats.toJson(); expect(statsJson.warnings).to.be.empty; expect(statsJson.errors[0].message).to.eql( - `Please check your InjectManifest plugin configuration:\n[WebpackInjectManifest] 'invalid' property is not expected to be here. Did you mean property 'include'?`, + `Please check your InjectManifest plugin configuration:\n[WebpackInjectManifest] 'invalid' property is not expected to be here. Did you mean property 'include'?`, ); done(); @@ -81,7 +91,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should lead to a webpack compilation error when the swSrc contains multiple injection points`, function(done) { + it(`should lead to a webpack compilation error when the swSrc contains multiple injection points`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -94,7 +104,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'bad-multiple-injection.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'bad-multiple-injection.js', + ), }), ], }; @@ -106,7 +122,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const statsJson = stats.toJson(); expect(statsJson.warnings).to.be.empty; expect(statsJson.errors[0].message).to.eql( - `Multiple instances of self.__WB_MANIFEST were found in your SW source. Include it only once. For more info, see https://github.com/GoogleChrome/workbox/issues/2681`, + `Multiple instances of self.__WB_MANIFEST were found in your SW source. Include it only once. For more info, see https://github.com/GoogleChrome/workbox/issues/2681`, ); done(); @@ -117,8 +133,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple chunks`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] Multiple chunks`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -151,15 +167,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -170,7 +192,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should honor the 'chunks' allowlist config`, function(done) { + it(`should honor the 'chunks' allowlist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -205,15 +227,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -224,7 +252,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function(done) { + it(`should honor the 'chunks' allowlist config, including children created via SplitChunksPlugin`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -266,15 +294,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -285,7 +319,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should honor the 'excludeChunks' denylist config`, function(done) { + it(`should honor the 'excludeChunks' denylist config`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -320,15 +354,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -339,7 +379,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function(done) { + it(`should honor setting both the 'chunks' and 'excludeChunks', with the denylist taking precedence`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -375,12 +415,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -392,8 +437,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] html-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -427,16 +472,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, { - revision: null, - url: /^entry2-[0-9a-f]{20}\.js$/, - }, { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: null, + url: /^entry2-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + ], + {}, + ], + ], }, }); @@ -448,8 +502,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function() { - it(`should work when called without any parameters`, function(done) { + describe(`[workbox-webpack-plugin] copy-webpack-plugin and a single chunk`, function () { + it(`should work when called without any parameters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -459,10 +513,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -483,44 +541,49 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: /^[0-9a-f]{32}$/, - url: 'images/example-jpeg.jpg', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'images/example-jpeg.jpg', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -532,8 +595,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function() { - it(`should update the sourcemap to account for manifest injection`, function(done) { + describe(`[workbox-webpack-plugin] Sourcemap manipulation`, function () { + it(`should update the sourcemap to account for manifest injection`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -561,9 +624,11 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { expect(files).to.have.length(4); const expectedSourcemap = await fse.readJSON( - upath.join(__dirname, 'static', 'expected-service-worker.js.map')); + upath.join(__dirname, 'static', 'expected-service-worker.js.map'), + ); const actualSourcemap = await fse.readJSON( - upath.join(outputDir, 'service-worker.js.map')); + upath.join(outputDir, 'service-worker.js.map'), + ); // The mappings will vary depending on the webpack version. delete expectedSourcemap.mappings; @@ -575,10 +640,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -589,7 +661,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should handle a custom output.sourceMapFilename`, function(done) { + it(`should handle a custom output.sourceMapFilename`, function (done) { const outputDir = tempy.directory(); const sourceMapFilename = upath.join('subdir', '[file].map'); @@ -620,9 +692,11 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { expect(files).to.have.length(4); const expectedSourcemap = await fse.readJSON( - upath.join(__dirname, 'static', 'expected-service-worker.js.map')); + upath.join(__dirname, 'static', 'expected-service-worker.js.map'), + ); const actualSourcemap = await fse.readJSON( - upath.join(outputDir, 'subdir', 'service-worker.js.map')); + upath.join(outputDir, 'subdir', 'service-worker.js.map'), + ); // The mappings will vary depending on the webpack version. delete expectedSourcemap.mappings; @@ -634,10 +708,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -648,9 +729,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should not fail if the sourcemap is missing from the assets`, function(done) { + it(`should not fail if the sourcemap is missing from the assets`, function (done) { const outputDir = tempy.directory(); - const swSrc = upath.join(__dirname, '..', '..', 'static', 'sw-src-missing-sourcemap.js'); + const swSrc = upath.join( + __dirname, + '..', + '..', + 'static', + 'sw-src-missing-sourcemap.js', + ); const config = { mode: 'development', @@ -681,10 +768,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -696,7 +790,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); // See https://github.com/GoogleChrome/workbox/issues/2729 - it(`should produce valid JavaScript when eval-cheap-source-map and minimization are used`, function(done) { + it(`should produce valid JavaScript when eval-cheap-source-map and minimization are used`, function (done) { const outputDir = tempy.directory(); const config = { @@ -712,7 +806,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'module-import-sw.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'module-import-sw.js', + ), swDest: 'service-worker.js', }), ], @@ -743,7 +843,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); // See https://github.com/GoogleChrome/workbox/issues/2729 - it(`should produce valid JavaScript when eval-cheap-source-map is used without minimization`, function(done) { + it(`should produce valid JavaScript when eval-cheap-source-map is used without minimization`, function (done) { const outputDir = tempy.directory(); const config = { @@ -759,7 +859,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }, plugins: [ new InjectManifest({ - swSrc: upath.join(__dirname, '..', '..', 'static', 'module-import-sw.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'module-import-sw.js', + ), swDest: 'service-worker.js', }), ], @@ -790,8 +896,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function() { - it(`should exclude .map and manifest.js files by default`, function(done) { + describe(`[workbox-webpack-plugin] Filtering via include/exclude`, function () { + it(`should exclude .map and manifest.js files by default`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -825,16 +931,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest.json', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'not-ignored.js', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest.json', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'not-ignored.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -845,7 +960,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should allow developers to override the default exclude filter`, function(done) { + it(`should allow developers to override the default exclude filter`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -876,10 +991,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'manifest-normally-ignored.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'manifest-normally-ignored.js', + }, + ], + {}, + ], + ], }, }); @@ -890,7 +1012,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should allow developers to allowlist via include`, function(done) { + it(`should allow developers to allowlist via include`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -900,10 +1022,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -925,16 +1051,25 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], }, }); @@ -945,7 +1080,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should allow developers to combine the include and exclude filters`, function(done) { + it(`should allow developers to combine the include and exclude filters`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -955,10 +1090,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -981,13 +1120,21 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + ], + {}, + ], + ], }, }); @@ -999,8 +1146,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] swDest variations`, function() { - it(`should work when swDest is an absolute path`, function(done) { + describe(`[workbox-webpack-plugin] swDest variations`, function () { + it(`should work when swDest is an absolute path`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1030,10 +1177,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -1045,8 +1199,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function() { - it(`should warn when when passed a non-existent chunk`, function(done) { + describe(`[workbox-webpack-plugin] Reporting webpack warnings`, function () { + it(`should warn when when passed a non-existent chunk`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1074,7 +1228,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const statsJson = stats.toJson(); expect(statsJson.errors).to.be.empty; expect(statsJson.warnings[0].message).to.eql( - `The chunk 'doesNotExist' was provided in your Workbox chunks config, but was not found in the compilation.`, + `The chunk 'doesNotExist' was provided in your Workbox chunks config, but was not found in the compilation.`, ); const files = await globby('**', {cwd: outputDir}); @@ -1084,12 +1238,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1100,7 +1259,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function(done) { + it(`should add maximumFileSizeToCacheInBytes warnings to compilation.warnings`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1112,10 +1271,14 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { path: outputDir, }, plugins: [ - new CopyWebpackPlugin({patterns: [{ - from: SRC_DIR, - to: outputDir, - }]}), + new CopyWebpackPlugin({ + patterns: [ + { + from: SRC_DIR, + to: outputDir, + }, + ], + }), new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', @@ -1134,7 +1297,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { try { const statsJson = stats.toJson('verbose'); expect(statsJson.warnings[0].message).to.eql( - `images/example-jpeg.jpg is 15.3 kB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.`, + `images/example-jpeg.jpg is 15.3 kB, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.`, ); const swFile = upath.join(outputDir, 'service-worker.js'); @@ -1146,44 +1309,49 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^entry1-[0-9a-f]{20}\.js$/, - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'images/web-fundamentals-icon192x192.png', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'index.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-1.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'page-2.html', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'splitChunksEntry.js', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-1.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'styles/stylesheet-2.css', - }, - { - revision: /^[0-9a-f]{32}$/, - url: 'webpackEntry.js', - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^entry1-[0-9a-f]{20}\.js$/, + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'images/web-fundamentals-icon192x192.png', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'index.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-1.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'page-2.html', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'splitChunksEntry.js', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-1.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'styles/stylesheet-2.css', + }, + { + revision: /^[0-9a-f]{32}$/, + url: 'webpackEntry.js', + }, + ], + {}, + ], + ], }, }); @@ -1195,8 +1363,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Customizing output paths and names`, function() { - it(`should honor publicPath`, function(done) { + describe(`[workbox-webpack-plugin] Customizing output paths and names`, function () { + it(`should honor publicPath`, function (done) { const outputDir = tempy.directory(); const publicPath = '/testing/'; const config = { @@ -1230,12 +1398,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[ - { - revision: null, - url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, - }, - ], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^\/testing\/entry1-[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1247,8 +1420,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest transformations`, function() { - it(`should use dontCacheBustURLsMatching`, function(done) { + describe(`[workbox-webpack-plugin] Manifest transformations`, function () { + it(`should use dontCacheBustURLsMatching`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1279,10 +1452,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - url: /^main\.[0-9a-f]{20}\.js$/, - revision: null, - }], {}]], + precacheAndRoute: [ + [ + [ + { + url: /^main\.[0-9a-f]{20}\.js$/, + revision: null, + }, + ], + {}, + ], + ], }, }); @@ -1293,7 +1473,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should use modifyURLPrefix`, function(done) { + it(`should use modifyURLPrefix`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1327,10 +1507,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^https:\/\/example\.org\/main\.[0-9a-f]{20}\.js/, + }, + ], + {}, + ], + ], }, }); @@ -1341,9 +1528,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should use webpackCompilationPlugins with DefinePlugin`, function(done) { + it(`should use webpackCompilationPlugins with DefinePlugin`, function (done) { const prefix = 'replaced-by-define-plugin'; - const swSrc = upath.join(__dirname, '..', '..', 'static', 'sw-src-define-plugin.js'); + const swSrc = upath.join( + __dirname, + '..', + '..', + 'static', + 'sw-src-define-plugin.js', + ); const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1378,10 +1571,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { entryPoint: 'injectManifest', expectedMethodCalls: { setCacheNameDetails: [[{prefix}]], - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1392,7 +1592,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should use manifestTransforms`, function(done) { + it(`should use manifestTransforms`, function (done) { const outputDir = tempy.directory(); const warningMessage = 'test warning'; const config = { @@ -1406,24 +1606,26 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { new InjectManifest({ swSrc: SW_SRC, swDest: 'service-worker.js', - manifestTransforms: [(manifest, compilation) => { - expect(manifest).to.have.lengthOf(1); - expect(manifest[0].size).to.eql(30); - expect(manifest[0].url.startsWith('main.')).to.be.true; - expect(manifest[0].revision).to.be.null; - expect(compilation).to.exist; - - manifest = manifest.map((entry) => { - entry.url += '-suffix'; - entry.revision = null; - return entry; - }); - - return { - manifest, - warnings: [warningMessage], - }; - }], + manifestTransforms: [ + (manifest, compilation) => { + expect(manifest).to.have.lengthOf(1); + expect(manifest[0].size).to.eql(30); + expect(manifest[0].url.startsWith('main.')).to.be.true; + expect(manifest[0].revision).to.be.null; + expect(compilation).to.exist; + + manifest = manifest.map((entry) => { + entry.url += '-suffix'; + entry.revision = null; + return entry; + }); + + return { + manifest, + warnings: [warningMessage], + }; + }, + ], }), ], }; @@ -1444,10 +1646,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main.[0-9a-f]{20}\.js-suffix$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main.[0-9a-f]{20}\.js-suffix$/, + }, + ], + {}, + ], + ], }, }); @@ -1459,8 +1668,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] TypeScript compilation`, function() { - it(`should rename a swSrc with a .ts extension to .js`, function(done) { + describe(`[workbox-webpack-plugin] TypeScript compilation`, function () { + it(`should rename a swSrc with a .ts extension to .js`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1492,9 +1701,9 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function() { + describe(`[workbox-webpack-plugin] Multiple invocation scenarios`, function () { // See https://github.com/GoogleChrome/workbox/issues/2158 - it(`should support multiple compilations using the same plugin instance`, async function() { + it(`should support multiple compilations using the same plugin instance`, async function () { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1543,7 +1752,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { } }); - it(`should only log once per invocation when using multiple plugin instances`, async function() { + it(`should only log once per invocation when using multiple plugin instances`, async function () { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1597,9 +1806,9 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Multiple plugin instances`, function() { + describe(`[workbox-webpack-plugin] Multiple plugin instances`, function () { // See https://github.com/GoogleChrome/workbox/issues/2181 - it(`should not list the swDest from one plugin in the other's manifest`, function(done) { + it(`should not list the swDest from one plugin in the other's manifest`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'production', @@ -1637,10 +1846,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile: sw1File, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1648,10 +1864,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile: sw2File, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1663,8 +1886,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Manifest injection in development mode`, function() { - it(`should produce valid, parsable JavaScript`, function(done) { + describe(`[workbox-webpack-plugin] Manifest injection in development mode`, function () { + it(`should produce valid, parsable JavaScript`, function (done) { const outputDir = tempy.directory(); const config = { mode: 'development', @@ -1696,10 +1919,17 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { swFile: swFile, entryPoint: 'injectManifest', expectedMethodCalls: { - precacheAndRoute: [[[{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }], {}]], + precacheAndRoute: [ + [ + [ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ], + {}, + ], + ], }, }); @@ -1711,8 +1941,8 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - describe(`[workbox-webpack-plugin] Non-compilation scenarios`, function() { - it(`should error when compileSrc is false and webpackCompilationPlugins is used`, function(done) { + describe(`[workbox-webpack-plugin] Non-compilation scenarios`, function () { + it(`should error when compileSrc is false and webpackCompilationPlugins is used`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1726,7 +1956,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.json', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.json'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.json', + ), webpackCompilationPlugins: [{}], }), ], @@ -1739,7 +1975,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const statsJson = stats.toJson(); expect(statsJson.errors).to.be.empty; expect(statsJson.warnings[0].message).to.eql( - 'compileSrc is false, so the webpackCompilationPlugins option will be ignored.', + 'compileSrc is false, so the webpackCompilationPlugins option will be ignored.', ); done(); @@ -1749,7 +1985,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should support injecting a manifest into a JSON file`, function(done) { + it(`should support injecting a manifest into a JSON file`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1763,7 +1999,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.json', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.json'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.json', + ), }), ], }; @@ -1776,11 +2018,15 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(2); - const manifest = await fse.readJSON(upath.join(outputDir, 'injected-manifest.json')); - expect(manifest).to.matchPattern([{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }]); + const manifest = await fse.readJSON( + upath.join(outputDir, 'injected-manifest.json'), + ); + expect(manifest).to.matchPattern([ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ]); done(); } catch (error) { @@ -1789,7 +2035,7 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { }); }); - it(`should support injecting a manifest into a CJS module`, function(done) { + it(`should support injecting a manifest into a CJS module`, function (done) { const outputDir = tempy.directory(); const config = { @@ -1803,7 +2049,13 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { new InjectManifest({ compileSrc: false, swDest: 'injected-manifest.js', - swSrc: upath.join(__dirname, '..', '..', 'static', 'injected-manifest.js'), + swSrc: upath.join( + __dirname, + '..', + '..', + 'static', + 'injected-manifest.js', + ), }), ], }; @@ -1816,11 +2068,16 @@ describe(`[workbox-webpack-plugin] InjectManifest with webpack v5`, function() { const files = await globby('**', {cwd: outputDir}); expect(files).to.have.length(2); - const manifest = require(upath.join(outputDir, 'injected-manifest.js')); - expect(manifest).to.matchPattern([{ - revision: null, - url: /^main\.[0-9a-f]{20}\.js$/, - }]); + const manifest = require(upath.join( + outputDir, + 'injected-manifest.js', + )); + expect(manifest).to.matchPattern([ + { + revision: null, + url: /^main\.[0-9a-f]{20}\.js$/, + }, + ]); done(); } catch (error) { diff --git a/test/workbox-webpack-plugin/node/v5/lib/create-webpack-asset-plugin.js b/test/workbox-webpack-plugin/node/v5/lib/create-webpack-asset-plugin.js index a1c4a6c6c..a79bfa1c5 100644 --- a/test/workbox-webpack-plugin/node/v5/lib/create-webpack-asset-plugin.js +++ b/test/workbox-webpack-plugin/node/v5/lib/create-webpack-asset-plugin.js @@ -17,12 +17,8 @@ class CreateWebpackAssetPlugin { } apply(compiler) { - compiler.hooks.thisCompilation.tap( - this.constructor.name, - (compilation) => compilation.emitAsset( - this.name, - new sources.RawSource(this.name), - ), + compiler.hooks.thisCompilation.tap(this.constructor.name, (compilation) => + compilation.emitAsset(this.name, new sources.RawSource(this.name)), ); } } diff --git a/test/workbox-webpack-plugin/static/example-project-1/index.html b/test/workbox-webpack-plugin/static/example-project-1/index.html index 070a6d27e..bfc1ee34b 100644 --- a/test/workbox-webpack-plugin/static/example-project-1/index.html +++ b/test/workbox-webpack-plugin/static/example-project-1/index.html @@ -4,12 +4,12 @@

    Index

    // Helper function which returns a promise which resolves once the service worker registration // is past the "installing" state. function waitUntilInstalled(registration) { - return new Promise(function(resolve, reject) { + return new Promise(function (resolve, reject) { if (registration.installing) { // If the current registration represents the "installing" service worker, then wait // until the installation step (during which the resources are pre-fetched) completes // to display the file list. - registration.installing.addEventListener('statechange', function(e) { + registration.installing.addEventListener('statechange', function (e) { if (e.target.state === 'installed') { resolve(); } else if (e.target.state === 'redundant') { @@ -35,40 +35,42 @@

    Index

    } searchParams[split[0]] = decodeURIComponent(split[1]); }); - navigator.serviceWorker.register(searchParams.sw) - .then((registration) => { - return waitUntilInstalled(registration); - }) - .then(() => { - return window.caches.keys() - .then(keys => { - return window.caches.open(keys[0]); + navigator.serviceWorker + .register(searchParams.sw) + .then((registration) => { + return waitUntilInstalled(registration); }) - .then((cache) => { - return cache.keys(); - }); - }) - .then((entries) => { - window.__testresult = { - entries: entries.map((entry) => { - return entry.url; - }) - }; - }) - .catch((err) => { - document.body.style.color = 'red'; - document.body.innerHTML = `

    ${err.message}

    + .then(() => { + return window.caches + .keys() + .then((keys) => { + return window.caches.open(keys[0]); + }) + .then((cache) => { + return cache.keys(); + }); + }) + .then((entries) => { + window.__testresult = { + entries: entries.map((entry) => { + return entry.url; + }), + }; + }) + .catch((err) => { + document.body.style.color = 'red'; + document.body.innerHTML = `

    ${err.message}

    ${err.stack}
    `; - console.error(err.message) - console.error(err.stack); + console.error(err.message); + console.error(err.stack); - // This is just to help with local development so we know there is an error - setTimeout(() => { - window.__testresult = { - error: err - }; - }, 5 * 1000); - }); + // This is just to help with local development so we know there is an error + setTimeout(() => { + window.__testresult = { + error: err, + }; + }, 5 * 1000); + }); diff --git a/test/workbox-window/integration/test-all.js b/test/workbox-window/integration/test-all.js index 25de37eec..46f6e3fe8 100644 --- a/test/workbox-window/integration/test-all.js +++ b/test/workbox-window/integration/test-all.js @@ -8,10 +8,16 @@ const {expect} = require('chai'); -const {executeAsyncAndCatch} = require('../../../infra/testing/webdriver/executeAsyncAndCatch'); +const { + executeAsyncAndCatch, +} = require('../../../infra/testing/webdriver/executeAsyncAndCatch'); const {runUnitTests} = require('../../../infra/testing/webdriver/runUnitTests'); -const {IframeManager} = require('../../../infra/testing/webdriver/IframeManager'); -const {unregisterAllSWs} = require('../../../infra/testing/webdriver/unregisterAllSWs'); +const { + IframeManager, +} = require('../../../infra/testing/webdriver/IframeManager'); +const { + unregisterAllSWs, +} = require('../../../infra/testing/webdriver/unregisterAllSWs'); const {windowLoaded} = require('../../../infra/testing/webdriver/windowLoaded'); const templateData = require('../../../infra/testing/server/template-data'); @@ -21,20 +27,20 @@ const {webdriver, server} = global.__workbox; const testServerOrigin = server.getAddress(); const testPath = `${testServerOrigin}/test/workbox-window/static/`; -describe(`[workbox-window]`, function() { - it(`passes all window unit tests`, async function() { +describe(`[workbox-window]`, function () { + it(`passes all window unit tests`, async function () { await runUnitTests('/test/workbox-window/window/'); }); }); -describe(`[workbox-window] Workbox`, function() { - beforeEach(async function() { +describe(`[workbox-window] Workbox`, function () { + beforeEach(async function () { templateData.assign({version: '1'}); await webdriver.get(testPath); await windowLoaded(); }); - afterEach(async function() { + afterEach(async function () { try { await unregisterAllSWs(); } catch (error) { @@ -43,7 +49,7 @@ describe(`[workbox-window] Workbox`, function() { }); describe('register', () => { - it(`registers a new service worker`, async function() { + it(`registers a new service worker`, async function () { const result = await executeAsyncAndCatch(async (cb) => { try { const wb = new Workbox('sw-clients-claim.js.njk'); @@ -61,7 +67,7 @@ describe(`[workbox-window] Workbox`, function() { expect(result.scriptURL).to.equal(`${testPath}sw-clients-claim.js.njk`); }); - it(`reports all events for a new SW registration`, async function() { + it(`reports all events for a new SW registration`, async function () { const result = await executeAsyncAndCatch(async (cb) => { try { const wb = new Workbox('sw-clients-claim.js.njk'); @@ -104,7 +110,7 @@ describe(`[workbox-window] Workbox`, function() { expect(result.waitingSpyCallCount).to.equal(0); }); - it(`reports all events for an updated SW registration`, async function() { + it(`reports all events for an updated SW registration`, async function () { const result = await executeAsyncAndCatch(async (cb) => { try { const wb1 = new Workbox('sw-clients-claim.js.njk?v=1'); @@ -159,7 +165,7 @@ describe(`[workbox-window] Workbox`, function() { expect(result.controllingSpyCallCount).to.equal(1); }); - it(`reports all events for an external SW registration`, async function() { + it(`reports all events for an external SW registration`, async function () { const iframeManager = new IframeManager(webdriver); await executeAsyncAndCatch(async (cb) => { diff --git a/test/workbox-window/static/index.html b/test/workbox-window/static/index.html index 8a1ef4a8f..6ae0205fb 100644 --- a/test/workbox-window/static/index.html +++ b/test/workbox-window/static/index.html @@ -7,37 +7,39 @@ https://opensource.org/licenses/MIT. --> - - - Workbox Integration Tests + + + Workbox Integration Tests - - + + - - - - - -

    You need to manually register a service worker

    + + + + + +

    You need to manually register a service worker

    - - + // Returns a promise that resolves when both the activated and controlling + // events have fired on the Workbox object. + window.activatedAndControlling = (wb) => { + const activatedPromise = new Promise((resolve) => { + wb.addEventListener('activated', () => resolve()); + }); + const controllingPromise = new Promise((resolve) => { + wb.addEventListener('controlling', () => resolve()); + }); + return Promise.all([activatedPromise, controllingPromise]); + }; + + diff --git a/test/workbox-window/window/test-Workbox.mjs b/test/workbox-window/window/test-Workbox.mjs index 30f8b15b5..5e71095a1 100644 --- a/test/workbox-window/window/test-Workbox.mjs +++ b/test/workbox-window/window/test-Workbox.mjs @@ -9,8 +9,11 @@ import {Workbox} from '/__WORKBOX/buildFile/workbox-window'; const isDev = () => { - return self.process && self.process.env && - self.process.env.NODE_ENV !== 'production'; + return ( + self.process && + self.process.env && + self.process.env.NODE_ENV !== 'production' + ); }; const sleep = async (ms) => { @@ -47,8 +50,10 @@ const uniq = (() => { const stubAlreadyControllingSW = async (scriptURL) => { await navigator.serviceWorker.register(scriptURL); await waitUntil(() => { - return navigator.serviceWorker.controller && - navigator.serviceWorker.controller.scriptURL.endsWith(scriptURL); + return ( + navigator.serviceWorker.controller && + navigator.serviceWorker.controller.scriptURL.endsWith(scriptURL) + ); }); }; @@ -80,7 +85,9 @@ const updateVersion = async (version, scriptURL) => { const assertMatchesWorkboxEvent = (event, props) => { for (const [key, value] of Object.entries(props)) { if (key === 'originalEvent' && typeof value !== 'undefined') { - expect(event.originalEvent.type, `${key} doesn't match`).to.equal(value.type); + expect(event.originalEvent.type, `${key} doesn't match`).to.equal( + value.type, + ); } else { expect(event[key], `${key} doesn't match`).to.equal(value); } @@ -89,7 +96,7 @@ const assertMatchesWorkboxEvent = (event, props) => { const sandbox = sinon.createSandbox(); -describe(`[workbox-window] Workbox`, function() { +describe(`[workbox-window] Workbox`, function () { // Since it's not possible to completely unregister a controlling SW from // a page (without closing all clients, including the current window), it's // also not possible to run unit tests all from a fresh start in a single @@ -98,7 +105,7 @@ describe(`[workbox-window] Workbox`, function() { // tests with a controlling SW and only test the things that don't need to // assert fresh-install behavior. Anything that does must be tested with // integration tests. - beforeEach(async function() { + beforeEach(async function () { const scriptURL = uniq('sw-clients-claim.js.njk'); await updateVersion('1.0.0', scriptURL); await stubAlreadyControllingSW(scriptURL); @@ -110,17 +117,17 @@ describe(`[workbox-window] Workbox`, function() { sandbox.spy(console, 'error'); }); - afterEach(async function() { + afterEach(async function () { sandbox.restore(); }); - describe(`constructor`, function() { - it(`creates an instance of the Workbox class`, async function() { + describe(`constructor`, function () { + it(`creates an instance of the Workbox class`, async function () { const wb = new Workbox(uniq('sw-clients-claim.js.njk')); expect(wb).to.be.instanceOf(Workbox); }); - it(`does not register a SW`, function(done) { + it(`does not register a SW`, function (done) { sandbox.spy(navigator.serviceWorker, 'register'); new Workbox(uniq('sw-clients-claim.js.njk')); @@ -135,8 +142,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`register`, function() { - it(`registers a service worker if the window is loaded`, async function() { + describe(`register`, function () { + it(`registers a service worker if the window is loaded`, async function () { sandbox.spy(navigator.serviceWorker, 'register'); sandbox.spy(self, 'addEventListener'); @@ -151,7 +158,7 @@ describe(`[workbox-window] Workbox`, function() { expect(navigator.serviceWorker.register.args[0][0]).to.equal(scriptURL); }); - it(`defers registration until after load by default`, async function() { + it(`defers registration until after load by default`, async function () { sandbox.spy(navigator.serviceWorker, 'register'); sandbox.spy(self, 'addEventListener'); @@ -168,7 +175,7 @@ describe(`[workbox-window] Workbox`, function() { expect(self.addEventListener.args[0][0]).to.equal('load'); }); - it(`supports not deferring until load`, async function() { + it(`supports not deferring until load`, async function () { sandbox.spy(navigator.serviceWorker, 'register'); sandbox.spy(self, 'addEventListener'); @@ -184,7 +191,7 @@ describe(`[workbox-window] Workbox`, function() { expect(self.addEventListener.calledWith('load')).to.not.equal(true); }); - it(`errors when registration fails`, async function() { + it(`errors when registration fails`, async function () { const wb = new Workbox(uniq('sw-error.js')); try { @@ -197,8 +204,8 @@ describe(`[workbox-window] Workbox`, function() { } }); - describe(`logs in development-only`, function() { - it(`(debug) if a SW with the same script URL is already controlling the page`, async function() { + describe(`logs in development-only`, function () { + it(`(debug) if a SW with the same script URL is already controlling the page`, async function () { if (!isDev()) this.skip(); // Gets the URL of the currently controlling SW. @@ -211,7 +218,7 @@ describe(`[workbox-window] Workbox`, function() { expect(console.debug.args[0][2]).to.match(/same/i); }); - it(`(debug) if a SW with a different script URL is already controlling the page`, async function() { + it(`(debug) if a SW with a different script URL is already controlling the page`, async function () { if (!isDev()) this.skip(); const wb = new Workbox(uniq('sw-no-skip-waiting.js.njk')); @@ -222,7 +229,7 @@ describe(`[workbox-window] Workbox`, function() { expect(console.debug.args[0][2]).to.match(/new/i); }); - it(`(info) when registration is successful`, async function() { + it(`(info) when registration is successful`, async function () { if (!isDev()) this.skip(); sandbox.spy(navigator.serviceWorker, 'register'); @@ -234,7 +241,7 @@ describe(`[workbox-window] Workbox`, function() { expect(console.log.args[0][2]).to.match(/success/i); }); - it(`(warn) when the registered SW is not in scope for the current page`, async function() { + it(`(warn) when the registered SW is not in scope for the current page`, async function () { if (!isDev()) this.skip(); sandbox.spy(navigator.serviceWorker, 'register'); @@ -246,7 +253,7 @@ describe(`[workbox-window] Workbox`, function() { expect(console.warn.args[0][2]).to.include('scope'); }); - it(`(warn) when a service worker is installed but now waiting`, async function() { + it(`(warn) when a service worker is installed but now waiting`, async function () { if (!isDev()) this.skip(); const wb = new Workbox(uniq('sw-no-skip-waiting.js.njk')); @@ -256,7 +263,7 @@ describe(`[workbox-window] Workbox`, function() { expect(console.warn.args[0][2]).to.match(/waiting/i); }); - it(`(error) when registration fails`, async function() { + it(`(error) when registration fails`, async function () { if (!isDev()) this.skip(); const wb = new Workbox(uniq('sw-error.js')); @@ -272,7 +279,7 @@ describe(`[workbox-window] Workbox`, function() { } }); - it(`(error) if calling register twice`, async function() { + it(`(error) if calling register twice`, async function () { if (!isDev()) this.skip(); const wb = new Workbox(uniq('sw-clients-claim.js.njk')); @@ -286,8 +293,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`update`, function() { - it(`calls update on the registration`, async function() { + describe(`update`, function () { + it(`calls update on the registration`, async function () { const scriptURL = navigator.serviceWorker.controller.scriptURL; const wb = new Workbox(scriptURL); const reg = await wb.register(); @@ -299,7 +306,7 @@ describe(`[workbox-window] Workbox`, function() { expect(reg.update.callCount).to.equal(1); }); - it(`triggers an updatefound event if the SW was updated`, async function() { + it(`triggers an updatefound event if the SW was updated`, async function () { const scriptURL = navigator.serviceWorker.controller.scriptURL; const wb = new Workbox(scriptURL); @@ -307,7 +314,9 @@ describe(`[workbox-window] Workbox`, function() { const reg = await wb.register(); const updatefoundPromise = new Promise((resolve) => { reg.addEventListener('updatefound', () => { - expect(reg.installing).to.not.equal(navigator.serviceWorker.controller); + expect(reg.installing).to.not.equal( + navigator.serviceWorker.controller, + ); resolve(); }); }); @@ -322,8 +331,8 @@ describe(`[workbox-window] Workbox`, function() { await updatefoundPromise; }); - describe(`logs in development-only`, function() { - it(`(error) if calling without registration`, async function() { + describe(`logs in development-only`, function () { + it(`(error) if calling without registration`, async function () { if (!isDev()) this.skip(); const wb = new Workbox(uniq('sw-clients-claim.js.njk')); @@ -335,8 +344,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`active`, function() { - it(`resolves as soon as the registered SW is active`, async function() { + describe(`active`, function () { + it(`resolves as soon as the registered SW is active`, async function () { const controllerBeforeTest = navigator.serviceWorker.controller; const scriptURL = controllerBeforeTest.scriptURL; const wb = new Workbox(scriptURL); @@ -350,7 +359,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw).to.equal(controllerBeforeTest); }); - it(`waits for an update if the scriptURLs don't match`, async function() { + it(`waits for an update if the scriptURLs don't match`, async function () { const controllerBeforeTest = navigator.serviceWorker.controller; const scriptURL = uniq('sw-clients-claim.js.njk'); const wb = new Workbox(scriptURL); @@ -365,8 +374,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`controlling`, function() { - it(`resolves as soon as the registered SW is controlling`, async function() { + describe(`controlling`, function () { + it(`resolves as soon as the registered SW is controlling`, async function () { const controllerBeforeTest = navigator.serviceWorker.controller; const scriptURL = controllerBeforeTest.scriptURL; const wb = new Workbox(scriptURL); @@ -380,7 +389,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw).to.equal(controllerBeforeTest); }); - it(`waits for an update if the scriptURLs don't match`, async function() { + it(`waits for an update if the scriptURLs don't match`, async function () { const controllerBeforeTest = navigator.serviceWorker.controller; const scriptURL = uniq('sw-clients-claim.js.njk'); const wb = new Workbox(scriptURL); @@ -395,8 +404,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`getSW`, function() { - it(`resolves as soon as it has a reference to the SW registered by this instance`, async function() { + describe(`getSW`, function () { + it(`resolves as soon as it has a reference to the SW registered by this instance`, async function () { const wb = new Workbox(uniq('sw-skip-waiting-deferred.js.njk')); // Intentionally do not await `register()`, so we can test that @@ -411,7 +420,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw).to.equal(reg.installing); }); - it(`resolves before updating if a SW with the same script URL is already controlling`, async function() { + it(`resolves before updating if a SW with the same script URL is already controlling`, async function () { const scriptURL = navigator.serviceWorker.controller.scriptURL; const wb = new Workbox(scriptURL); @@ -423,7 +432,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw).to.equal(navigator.serviceWorker.controller); }); - it(`resolves before updating if a SW with the same script URL is already waiting to install`, async function() { + it(`resolves before updating if a SW with the same script URL is already waiting to install`, async function () { const scriptURL = uniq('sw-no-skip-waiting.js.njk'); const wb1 = new Workbox(scriptURL); @@ -436,8 +445,9 @@ describe(`[workbox-window] Workbox`, function() { // about to be waiting. This is done to assert that if a matching // controller *and* waiting SW are found at registration time, the // `getSW()` method resolves to the waiting SW. - sandbox.stub(navigator.serviceWorker.controller, 'scriptURL') - .value(scriptURL); + sandbox + .stub(navigator.serviceWorker.controller, 'scriptURL') + .value(scriptURL); const wb2 = new Workbox(scriptURL); const reg2Promise = wb2.register(); @@ -447,7 +457,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw).to.equal(reg2.waiting); }); - it(`resolves as soon as an an update is found (if not already resolved)`, async function() { + it(`resolves as soon as an an update is found (if not already resolved)`, async function () { const wb = new Workbox(uniq('sw-clients-claim.js.njk')); wb.register(); @@ -455,7 +465,7 @@ describe(`[workbox-window] Workbox`, function() { expect(sw.state).to.equal('installing'); }); - it(`resolves to the new SW after an update is found`, async function() { + it(`resolves to the new SW after an update is found`, async function () { const scriptURL = navigator.serviceWorker.controller.scriptURL; // Update the SW after it's controlling so both an original compatible @@ -485,8 +495,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`messageSW`, function() { - it(`postMessages the registered service worker`, async function() { + describe(`messageSW`, function () { + it(`postMessages the registered service worker`, async function () { const wb = new Workbox(uniq('sw-message-reply.js')); await wb.register(); @@ -499,7 +509,7 @@ describe(`[workbox-window] Workbox`, function() { expect(messageSpy.args[0][0].data).to.equal('postMessage from SW!'); }); - it(`returns a promise that resolves with the SW's response (if any)`, async function() { + it(`returns a promise that resolves with the SW's response (if any)`, async function () { const wb = new Workbox(uniq('sw-message-reply.js')); wb.register(); @@ -507,7 +517,7 @@ describe(`[workbox-window] Workbox`, function() { expect(response).to.equal('Reply from SW!'); }); - it(`awaits registration if registration hasn't run`, async function() { + it(`awaits registration if registration hasn't run`, async function () { const wb = new Workbox(uniq('sw-message-reply.js')); setTimeout(() => wb.register(), 100); @@ -516,8 +526,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`messageSkipWaiting`, function() { - it(`posts the expected message to the waiting service worker`, async function() { + describe(`messageSkipWaiting`, function () { + it(`posts the expected message to the waiting service worker`, async function () { const scriptURL = uniq('sw-skip-waiting-on-message.js.njk'); const wb = new Workbox(scriptURL); @@ -547,7 +557,7 @@ describe(`[workbox-window] Workbox`, function() { expect(controllingSW.scriptURL).to.eql(scriptURL); }); - it(`does nothing if there's no waiting service worker`, async function() { + it(`does nothing if there's no waiting service worker`, async function () { const wb = new Workbox(uniq('sw-skip-waiting.js.njk')); await wb.register(); @@ -557,9 +567,9 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`events`, function() { - describe(`message`, function() { - it(`fires when a postMessage is received from the SW`, async function() { + describe(`events`, function () { + describe(`message`, function () { + it(`fires when a postMessage is received from the SW`, async function () { const wb = new Workbox(uniq('sw-message-reply.js')); await wb.register(); await wb.getSW(); @@ -580,7 +590,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`can receive a message prior to calling register but buffers them until after registration`, async function() { + it(`can receive a message prior to calling register but buffers them until after registration`, async function () { const scriptURL = navigator.serviceWorker.controller.scriptURL; const wb = new Workbox(scriptURL); @@ -589,10 +599,12 @@ describe(`[workbox-window] Workbox`, function() { // Simulate a message event sent from the controlling service worker // at page load time (prior to calling `register()`); - navigator.serviceWorker.dispatchEvent(new MessageEvent('message', { - data: 'postMessage from during page load!', - source: navigator.serviceWorker.controller, - })); + navigator.serviceWorker.dispatchEvent( + new MessageEvent('message', { + data: 'postMessage from during page load!', + source: navigator.serviceWorker.controller, + }), + ); expect(messageSpy.notCalled).to.be.true; @@ -608,7 +620,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`does not dispatch messages received from non-own service workers`, async function() { + it(`does not dispatch messages received from non-own service workers`, async function () { const wb = new Workbox(uniq('sw-clients-claim.js.njk')); const messageSpy = sandbox.spy(); @@ -616,10 +628,12 @@ describe(`[workbox-window] Workbox`, function() { // Simulate a message event sent from the controlling service worker // at page load time (prior to calling `register()`); - navigator.serviceWorker.dispatchEvent(new MessageEvent('message', { - data: 'postMessage from during page load!', - source: navigator.serviceWorker.controller, - })); + navigator.serviceWorker.dispatchEvent( + new MessageEvent('message', { + data: 'postMessage from during page load!', + source: navigator.serviceWorker.controller, + }), + ); expect(messageSpy.notCalled).to.be.true; @@ -630,8 +644,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`installed`, function() { - it(`fires the first time the registered SW is installed`, async function() { + describe(`installed`, function () { + it(`fires the first time the registered SW is installed`, async function () { const scriptURL = uniq('sw-clients-claim.js.njk'); const wb1 = new Workbox(scriptURL); @@ -694,8 +708,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`waiting`, function() { - it(`runs if the registered service worker is waiting`, async function() { + describe(`waiting`, function () { + it(`runs if the registered service worker is waiting`, async function () { const wb1 = new Workbox(uniq('sw-no-skip-waiting.js.njk')); const waiting1Spy = sandbox.spy(); wb1.addEventListener('waiting', waiting1Spy); @@ -732,7 +746,6 @@ describe(`[workbox-window] Workbox`, function() { originalEvent: {type: 'statechange'}, wasWaitingBeforeRegister: undefined, isExternal: false, - }); expect(waiting3Spy.callCount).to.equal(1); @@ -746,7 +759,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs if a service worker was already waiting at registration time`, async function() { + it(`runs if a service worker was already waiting at registration time`, async function () { const scriptURL = uniq('sw-no-skip-waiting.js.njk'); const wb1 = new Workbox(scriptURL); @@ -773,8 +786,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`activated`, function() { - it(`runs the first time the registered SW is activated`, async function() { + describe(`activated`, function () { + it(`runs the first time the registered SW is activated`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); const activated1Spy = sandbox.spy(); wb1.addEventListener('activated', activated1Spy); @@ -821,8 +834,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`controlling`, function() { - it(`runs the first time the registered SW is controlling`, async function() { + describe(`controlling`, function () { + it(`runs the first time the registered SW is controlling`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); const controlling1Spy = sandbox.spy(); wb1.addEventListener('controlling', controlling1Spy); @@ -883,7 +896,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs every time the registered SW is updated`, async function() { + it(`runs every time the registered SW is updated`, async function () { const scriptURL = uniq('sw-skip-waiting.js.njk'); const wb1 = new Workbox(scriptURL); const controlling1Spy = sandbox.spy(); @@ -929,8 +942,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`redundant`, function() { - it(`runs if the registered SW becomes redundant`, async function() { + describe(`redundant`, function () { + it(`runs if the registered SW becomes redundant`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); const redundantSpy = sandbox.spy(); wb1.addEventListener('redundant', redundantSpy); @@ -952,7 +965,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs in the case where the registered SW was already controlling`, async function() { + it(`runs in the case where the registered SW was already controlling`, async function () { const controllerBeforeTest = navigator.serviceWorker.controller; const scriptURL = controllerBeforeTest.scriptURL; const wb1 = new Workbox(scriptURL); @@ -978,8 +991,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`isExternal logic`, function() { - it(`runs when an external SW is found and installed`, async function() { + describe(`isExternal logic`, function () { + it(`runs when an external SW is found and installed`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); const externalInstalled1Spy = sandbox.spy(); wb1.addEventListener('installed', externalInstalled1Spy); @@ -1018,7 +1031,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs when an updated version of the registered SW is found after the update timeout`, async function() { + it(`runs when an updated version of the registered SW is found after the update timeout`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['performance'], }); @@ -1057,7 +1070,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs when an external SW is waiting`, async function() { + it(`runs when an external SW is waiting`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); const externalWaiting1Spy = sandbox.spy(); wb1.addEventListener('waiting', externalWaiting1Spy); @@ -1087,7 +1100,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs when an updated version of the registered SW is found after the update timeout and is waiting to activate`, async function() { + it(`runs when an updated version of the registered SW is found after the update timeout and is waiting to activate`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['performance'], }); @@ -1125,7 +1138,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs when an external SW is found and activated`, async function() { + it(`runs when an external SW is found and activated`, async function () { const wb1 = new Workbox(uniq('sw-clients-claim.js.njk')); await wb1.register(); await nextEvent(wb1, 'activated'); @@ -1146,7 +1159,7 @@ describe(`[workbox-window] Workbox`, function() { }); }); - it(`runs when an updated version of the registered SW is found after the update timeout and has activated`, async function() { + it(`runs when an updated version of the registered SW is found after the update timeout and has activated`, async function () { const clock = sandbox.useFakeTimers({ toFake: ['performance'], }); @@ -1183,8 +1196,8 @@ describe(`[workbox-window] Workbox`, function() { }); }); - describe(`removeEventListener()`, function() { - it(`will register and then unregister event listeners of a given type`, function() { + describe(`removeEventListener()`, function () { + it(`will register and then unregister event listeners of a given type`, function () { const eventType = 'testEventType'; const event = {type: eventType}; const eventListener1 = sandbox.stub(); diff --git a/tsconfig.json b/tsconfig.json index 48d8e0d23..b9f0d924c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,20 +17,20 @@ "files": ["./infra/type-overrides.d.ts"], "exclude": [], "references": [ - { "path": "./packages/workbox-broadcast-update/" }, - { "path": "./packages/workbox-background-sync/" }, - { "path": "./packages/workbox-build/" }, - { "path": "./packages/workbox-cacheable-response/" }, - { "path": "./packages/workbox-cli/" }, - { "path": "./packages/workbox-core/" }, - { "path": "./packages/workbox-expiration/" }, - { "path": "./packages/workbox-navigation-preload/" }, - { "path": "./packages/workbox-precaching/" }, - { "path": "./packages/workbox-range-requests/" }, - { "path": "./packages/workbox-recipes/" }, - { "path": "./packages/workbox-routing/" }, - { "path": "./packages/workbox-strategies/" }, - { "path": "./packages/workbox-streams/" }, - { "path": "./packages/workbox-window/" } + {"path": "./packages/workbox-broadcast-update/"}, + {"path": "./packages/workbox-background-sync/"}, + {"path": "./packages/workbox-build/"}, + {"path": "./packages/workbox-cacheable-response/"}, + {"path": "./packages/workbox-cli/"}, + {"path": "./packages/workbox-core/"}, + {"path": "./packages/workbox-expiration/"}, + {"path": "./packages/workbox-navigation-preload/"}, + {"path": "./packages/workbox-precaching/"}, + {"path": "./packages/workbox-range-requests/"}, + {"path": "./packages/workbox-recipes/"}, + {"path": "./packages/workbox-routing/"}, + {"path": "./packages/workbox-strategies/"}, + {"path": "./packages/workbox-streams/"}, + {"path": "./packages/workbox-window/"} ] } diff --git a/typescript.eslintrc.js b/typescript.eslintrc.js index 8b896ac3c..d23d38dcf 100644 --- a/typescript.eslintrc.js +++ b/typescript.eslintrc.js @@ -5,10 +5,7 @@ module.exports = { project: ['./packages/*/tsconfig.json'], tsconfigRootDir: __dirname, }, - plugins: [ - '@typescript-eslint', - 'jsdoc', - ], + plugins: ['@typescript-eslint', 'jsdoc'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/eslint-recommended', @@ -34,15 +31,15 @@ module.exports = { 'block-scoped-var': 'error', 'eol-last': 'error', 'eqeqeq': 'error', + 'indent': 'off', 'no-cond-assign': 'off', 'no-dupe-class-members': 'off', 'no-var': 'error', 'no-warning-comments': 'off', + 'operator-linebreak': 'off', 'prefer-const': 'error', 'prefer-spread': 'off', + 'space-before-function-paren': 'off', }, - ignorePatterns: [ - '**/_version.ts', - 'test/**', - ], + ignorePatterns: ['**/_version.ts', 'test/**'], };