Upstream version 8.37.180.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / LayoutTests / http / tests / serviceworker / resources / test-helpers.js
1 // Adapter for testharness.js-style tests with Service Workers
2
3 function service_worker_test(url, description) {
4     var t = async_test(description);
5     t.step(function() {
6         var scope = 'nonexistent';
7         service_worker_unregister_and_register(t, url, scope, onRegistered);
8
9         function onRegistered(worker) {
10             var messageChannel = new MessageChannel();
11             messageChannel.port1.onmessage = t.step_func(onMessage);
12             worker.postMessage({port:messageChannel.port2}, [messageChannel.port2]);
13         }
14
15         function onMessage(e) {
16             assert_equals(e.data, 'pass');
17             service_worker_unregister_and_done(t, scope);
18         }
19     });
20 }
21
22 function service_worker_unregister_and_register(test, url, scope, onregister) {
23     var options = scope ? { scope: scope } : {};
24     return navigator.serviceWorker.unregister(scope).then(
25         // FIXME: Wrap this with test.step_func once testharness.js is updated.
26         function() {
27             return navigator.serviceWorker.register(url, options);
28         },
29         unreached_rejection(test, 'Unregister should not fail')
30     ).then(
31         test.step_func(onregister),
32         unreached_rejection(test, 'Registration should not fail')
33     );
34 }
35
36 function service_worker_unregister_and_done(test, scope) {
37     return navigator.serviceWorker.unregister(scope).then(
38         test.done.bind(test),
39         unreached_rejection(test, 'Unregister should not fail'));
40 }
41
42 // Rejection-specific helper that provides more details
43 function unreached_rejection(test, prefix) {
44     return test.step_func(function(reason) {
45         assert_unreached(prefix + ': ' + reason.name);
46     });
47 }
48
49 // FIXME: Clean up the iframe when the test completes.
50 function with_iframe(url, f) {
51     return new Promise(function(resolve, reject) {
52         var frame = document.createElement('iframe');
53         frame.src = url;
54         frame.onload = function() {
55             if (f) {
56               f(frame);
57             }
58             resolve(frame);
59         };
60         document.body.appendChild(frame);
61     });
62 }
63
64 function normalizeURL(url) {
65   return new URL(url, document.location).toString().replace(/#.*$/, '');
66 }