我正在寻找一种方法来设置navigator.serviceWorker来对我的服务工作者进行单元测试。我当前的JSDOM设置如下所示:
import { JSDOM } from 'jsdom';
const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');
global.window = dom.window;
global.document = dom.window.document;
Object.keys(global.window).forEach(property => {
if (typeof global[property] === 'undefined') {
global[property] = global.window[property];
}
});
global.navigator = {
userAgent: 'node.js'
};
我已经尝试为global.navigator = ...
评论global.navigator = global.window.navigator
。但是,以下console.log(global.navigator.serviceWorker)
和console.log(navigator.serviceWorker)
都会在我的单元测试中返回undefined
:
describe('Service Worker', () => {
it('should register a service worker and cache files on install', () => {
console.log(navigator.serviceWorker); // undefined
// navigator.serviceWorker.register() // not used yet since undefined
});
});
答案 0 :(得分:1)
使用Object.defineProperty
方法创建新的serviceWorker
属性:
Object.defineProperty(global.navigator, 'serviceWorker', {
value: {
register: jest.fn() // Choose your favourite mocking library
}
});
将register
方法定义为模拟函数,将允许您监视对该函数的调用,并返回可以解析或拒绝的promise。
import sw from './service-worker';
describe('Service worker registration', () => {
it('call navigator.serviceWorker.register with the right URL', () => {
expect(navigator.serviceWorker.register).toHaveBeenCalledWith('/service-worker.js');
});
});