来自react-native的Jest mock DeviceEventEventEventEvent

gev0vcfq  于 11个月前  发布在  Jest
关注(0)|答案(1)|浏览(131)

我尝试使用jestreact-native模拟DeviceEventEmitter。实际代码分别在组件挂载和卸载时添加和删除侦听器。我尝试了很多解决方案,但都不起作用。
这是我试图嘲笑的几种方式。

// type 1
jest.mock('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter', () => {
  return {
     addListener: mockAddListener,
     remove: mockRemove
  }
});

// type 2
jest.mock('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter', () => {
  const DeviceEventEmitter = jest.requireActual('react-native/Libraries/EventEmitter/RCTDeviceEventEmitter');
  return DeviceEventEmitter;
});

字符串
有什么建议吗?

mnemlml8

mnemlml81#

经过大量的实验,试图模拟这一点,最后下面的模拟工作。

// Make sure you are using the right path for node_modules depending on your test file location
jest.mock('../../node_modules/react-native/Libraries/vendor/emitter/EventEmitter', () => {
    return class EventEmitter {
        emit = jest.fn()
        // Add other methods which ever you need to mock
    };
});

字符串
所以基本上DeviceEventEmitter扩展了EventEmitter。所以模拟EventEmitter并实现所需的方法是有效的。

相关问题