Last active
November 30, 2017 19:01
-
-
Save dkarmalita/7797cd776a4b63f32083ff212b16ec27 to your computer and use it in GitHub Desktop.
jsdom based browser environment setup for testing with mocha/chai stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { jsdom } from 'jsdom'; | |
const document = jsdom('<!DOCTYPE html><head></head><body></body></html>'); | |
const exposedProperties = ['window', 'navigator', 'document']; | |
global.document = document; | |
global.window = document.defaultView; | |
Object.keys(document.defaultView).forEach((property) => { | |
if (typeof global[property] === 'undefined') { | |
exposedProperties.push(property); | |
global[property] = document.defaultView[property]; | |
} | |
}); | |
global.navigator = { | |
userAgent: 'node.js', | |
}; | |
global.documentRef = document; | |
// Local store mock | |
const mockStorage = () => { | |
const storage = {}; | |
return { | |
setItem: (key, value = '') => { | |
storage[key] = value; | |
}, | |
getItem: key => storage[key], | |
removeItem: (key) => { | |
delete storage[key]; | |
}, | |
get length() { | |
return Object.keys(storage).length; | |
}, | |
key: (i) => { | |
const keys = Object.keys(storage); | |
return keys[i] || null; | |
}, | |
}; | |
}; | |
global.localStorage = mockStorage(); | |
global.sessionStorage = mockStorage(); | |
global.window.localStorage = mockStorage(); | |
global.window.sessionStorage = mockStorage(); | |
process.on('unhandledRejection', () => {}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment