开玩笑–模拟窗口或文档对象 [英] Jest – Mock Window or Document object

查看:1124
本文介绍了开玩笑–模拟窗口或文档对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Jest模拟(然后测试)Window或Document对象?尤其是当它具有尚未在文件中定义的嵌套函数时,例如,您正在测试.

How do you mock (and then test) the Window or Document object with Jest? Especially when it has nested functions that may not yet defined in the file you're testing E.g.

const foo = (payload) => {
    window.webkit.messageHandlers.execute.postMessage(payload)
    return true
}

// Jest: TypeError: Cannot read property 'messageHandlers' of undefined'

类似地,您将如何模拟document.location?例如

Similarly, how would you mock document.location? E.g.

const bar = (nonce, payload) => {
    document.location = 'native://somefeature/send?nonce=' + nonce + '&payload=' + payload
    return true
}

我正朝着:

describe('foo', () => {
  it('posts a message', () => {
    const payload = 'payload'
    window.webkit.messageHandlers.execute.postMessage = jest.fn()
    let result = foo(payload) 
    expect(window.webkit.messageHandlers.execute.postMessage).toHaveBeenCalledWith(payload)
  })    
})

我猜您会对document.location =做类似的事情.但是,那当然太简单了,并且不起作用.

I'm guessing you'd do something similar for document.location =. But of course that would be way too easy, and it does not work.

推荐答案

如果还没有找到答案,您应该可以像这样模拟它:

If you haven't found an answer already, you should be able to mock it like this:

  postMessageMock = jest.fn();
  Object.defineProperty(window, 'webkit', {
    value: { messageHandlers: { execute: { postMessage: postMessageMock } } },
  });

这篇关于开玩笑–模拟窗口或文档对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆