我有一个名为web3
的对象,我监听它上的事件并用于设置cookie:
import Cookies from 'universal-cookie'
import _ from 'lodash'
const cookies = new Cookies()
const setUserId = () => {
if (_.isUndefined(window.web3)) return
window.web3.currentProvider.publicConfigStore.on(
'update',
({ selectedAddress }) => {
cookies.set('userId', selectedAddress)
}
)
}
export default {
setUserId,
}
我试着开玩笑地测试这一点,但我坚持我应该怎么做:
1( 模拟Cookies
2( 模拟web3.currentProvider.publicConfigStore.on('update', ...)
有人能帮忙吗?
要模拟Cookies
,您需要模拟导入的模块,以便它返回一个函数,该函数使用作为模拟的set
方法返回一个对象。您可以只使用一个函数,因为在JavaScript中,类和函数之间没有真正的区别。
jest.mock('universal-cookie', ()=> jest.fn())
import Cookie from 'universal-cookie'
const setCookie = jest.fn()
Cookie.mockImplementation(()=> ({set: setCookie}))
如果你不需要检查set
函数,你也可以在一行中进行模拟:
jest.mock('universal-cookie', ()=> ()=> ({set: jest.fn()})
要访问全局命名空间(如window
(中的任何内容,您可以开玩笑地使用global
关键字来访问它;
const on = jest.fn()
global.web3 = {
currentProvider: {
publicConfigStore: {
on
}
}
}
最后一步是使用mock.calls
调用传递给on
的回调
on.mock.calls[0][1]({selectedAddress: 'someAddress'})