简体   繁体   中英

How to test the angular service worker

I'm registering my angular service worker (from @angular/PWA) in app.component.ts . I'm unable to determine how to register ngsw-worker.js in app.component.spec.ts . It's in the dist folder, as part of a production build (only available with --prod). My import in the test file looks like this:

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true }),

The error message: Failed to register a ServiceWorker for scope ('http://localhost:<port>/') with script ('http://localhost:<port>/ngsw-worker.js'): A bad HTTP response code (404) was received when fetching the script.

It doesn't look like ng test includes a --prod option

As it's the ngsw-worker , it uses this.scope.skipWaiting() during install and yield this.scope.clients.claim() during activate, so it seems as though registering the sw correctly in a unit test should do the trick.

I've looked through the localhost directory in devtools but I'm not seeing the sw anywhere.

Question: In light of the above, how can I register the ngsw-worker.js for testing purposes?

To be a bit more precise,

You have to first download http-server which is a "simple, zero-configuration command-line http server".

  1. Install http server on your laptop globally npm install --global http-server
  2. Build your project locally ng build --prod
  3. run http-server http-server -p 8080 -c-1 dist/<project-name> -c-1 = disable caching
  4. Then open your browser in incognito mode with this url http://localhost:8080/

For more information about it : https://angular.io/guide/service-worker-getting-started#serving-with-http-server

first build production and then run

http-server -p 8080 -c-1 dist/your-projectname

and open incognito tab and go to

localhost:8080

and test your service worker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM