在JEST和vue-test-utils中模拟window.document

时间:2019-11-20 10:09:04

标签: javascript unit-testing vue.js testing jestjs

我在测试中嘲笑window.document属性时遇到问题。我想测试一个简单的vuex操作,该操作使用favicon url来获取配置。接下来,设置图标图标。不幸的是,动作文件中的window.document对象没有被模拟功能取代。

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
},

和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 })
    })

致谢

0 个答案:

没有答案