OLD | NEW |
(Empty) | |
| 1 // Test helper that is meant as a mini test framework to be used from a service |
| 2 // worker that runs some tests and send results back to its client. |
| 3 // |
| 4 // A simple usage of this framework would consist of calling initialize() to |
| 5 // setup then runNextTestOrQuit() in order to start running the methods defined |
| 6 // by TESTS. Then, tests can start sending messages back to the client using |
| 7 // postMessage(). |
| 8 // |
| 9 // Example: |
| 10 // var TESTS = [ |
| 11 // function simpleTest() { |
| 12 // self.postMessage('you will receive this first'); |
| 13 // }, |
| 14 // function secondTest() { |
| 15 // self.postMessage('secondTest done!'); |
| 16 // runNextTestOrQuit(); |
| 17 // } |
| 18 // ]; |
| 19 // |
| 20 // initialize().runNextTestOrQuit(); |
| 21 // |
| 22 // In addition, there is a helper method meant to synthesized notificationclick |
| 23 // events sent to a service worker, see synthesizeNotificationClick. |
| 24 |
| 25 var client = null; |
| 26 var currentTest = -1; |
| 27 |
| 28 self.initialize = function() { |
| 29 return self.clients.getAll().then(function(clients) { |
| 30 client = clients[0]; |
| 31 }); |
| 32 } |
| 33 |
| 34 self.postMessage = function(msg) { |
| 35 client.postMessage(msg); |
| 36 } |
| 37 |
| 38 // Run the next test in TESTS if any. Otherwise sends a 'quit' message. and |
| 39 // stops. |
| 40 // In order for that call to succeed, the script MUST have a TESTS array |
| 41 // defined. |
| 42 self.runNextTestOrQuit = function() { |
| 43 ++currentTest; |
| 44 if (currentTest >= TESTS.length) { |
| 45 client.postMessage('quit'); |
| 46 return; |
| 47 } |
| 48 TESTS[currentTest](); |
| 49 } |
| 50 |
| 51 // This method will use the |client| in order to synthesize a notificationclick |
| 52 // event. The client will then use the testRunner. |
| 53 // The returned promise will be resolved with the notificationclick event |
| 54 // object. |
| 55 self.synthesizeNotificationClick = function() { |
| 56 var promise = new Promise(function(resolve) { |
| 57 var title = "fake notification"; |
| 58 registration.showNotification(title).then(function() { |
| 59 client.postMessage({type: 'click', title: title}); |
| 60 }); |
| 61 |
| 62 var handler = function(e) { |
| 63 resolve(e); |
| 64 e.notification.close(); |
| 65 self.removeEventListener('notificationclick', handler); |
| 66 }; |
| 67 |
| 68 self.addEventListener('notificationclick', handler); |
| 69 }); |
| 70 |
| 71 return promise; |
| 72 } |
OLD | NEW |