Jest - 模拟窗口或文档对象

时间:2017-07-19 20:27:10

标签: javascript unit-testing jestjs

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

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

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

同样,你会如何模仿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 =做了类似的事情。但当然这太容易了,而且不起作用。

1 个答案:

答案 0 :(得分:3)

如果您还没有找到答案,您应该能够像这样嘲笑:

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