【发布时间】:2021-10-06 23:17:40
【问题描述】:
我有一组在 Karma 中运行的集成测试。不幸的是,他们调用了一个外部的生产 API 端点。我不想调用集成测试,我正在探索我的选择。
我想知道服务人员是否是一个可行的解决方案。我的假设是它们不起作用,因为https://github.com/w3c/ServiceWorker/issues/1188 明确表示不支持跨域获取,并且 localhost 与生产 API 端点的来源不同。
为清楚起见,这是我正在运行的一些代码:
try {
const { scope, installing, waiting, active } = await navigator.serviceWorker.register('./base/htdocs/test/imageMock.sw.js');
console.log('ServiceWorker registration successful with scope: ', scope, installing, waiting, active);
(installing || waiting || active).addEventListener('statechange', (e) => {
console.log('state', e.target.state);
});
} catch (error) {
console.error('ServiceWorker registration failed: ', error);
}
和服务人员
// imageMock.sw.js
if (typeof self.skipWaiting === 'function') {
console.log('self.skipWaiting() is supported.');
self.addEventListener('install', (e) => {
// See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-global-scope-skipwaiting
e.waitUntil(self.skipWaiting());
});
} else {
console.log('self.skipWaiting() is not supported.');
}
if (self.clients && (typeof self.clients.claim === 'function')) {
console.log('self.clients.claim() is supported.');
self.addEventListener('activate', (e) => {
// See https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#clients-claim-method
e.waitUntil(self.clients.claim());
});
} else {
console.log('self.clients.claim() is not supported.');
}
self.addEventListener('fetch', (event) => {
console.log('fetching resource', event);
if (/\.jpg$/.test(event.request.url)) {
const response = new Response('<p>This is a response that comes from your service worker!</p>', {
headers: { 'Content-Type': 'text/html' },
});
event.respondWith(response);
}
});
当这段代码运行时,我会在控制台中看到
ServiceWorker registration successful with scope: http://localhost:9876/base/htdocs/test/ null null ServiceWorker
然后对https://<productionServer>.com/image.php 的请求不会被提取处理程序拦截。
在这种情况下没有办法拦截是正确的吗?
【问题讨论】:
标签: javascript karma-runner service-worker