I have a problem with mocking window.document
property in my test. I want to test a simple vuex action, which fetches config with favicon url. Next, favicon is being set. Unfortunately, window.document object in actions file is not replaced by mock function.
actions.js
const changeFavicon = (url) => {
try {
console.log(window.document.createElement) //always prints [Function: createElement] instead of [Function: mockConstructor]
let link = window.document.querySelector('link[rel*="icon"]') || window.document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = url;
window.document.getElementsByTagName('head')[0].appendChild(link);
} catch (e) {
console.log(e)
}
}
...
async fetchConfig({ commit }) {
const { data: config } = await api.get('config');
if (config.favicon_url) {
changeFavicon(config.favicon_url)
}
commit('setConfig', config);
return config
},
and actions.spec.js
it('should set favicon', async () => {
const document = window.document
Object.defineProperty(global, 'document', {
value: {
createElement: jest.fn(),
addEventListener: jest.fn()
}
})
console.log(global.document.createElement) // printss correctly [Function: mockConstructor]
expect(global.document.createElement).toHaveBeenCalled()
Object.defineProperty(window, 'document', { value: document })
})
Regards
Aucun commentaire:
Enregistrer un commentaire