mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

Can't mock custom module #61

Open chapati23 opened 7 years ago

chapati23 commented 7 years ago

My Module:

// ./App/Services/MyBridge
import { NativeModules } from 'react-native'
export const MyBridge = NativeModules.MyBridge
export default MyBridge

My Mock:

// ./testSetup.js
mockery.enable()
mockery.registerAllowable('./App/Services/MyBridge', {
  nativeCall: () => {}
})

mockery.registerMock('./App/Services/MyBridge', {
  nativeCall: () => {}
})

Expected Behavior MyBridge.nativeCall is mocked

Actual Behavior Error message during test run Error: Cannot read property 'nativeCall' of undefined

I can't, for the life of me, figure this out. Mocking 3rd party modules works fine. Any ideas? (mockery@2.0.0)

chapati23 commented 7 years ago

Found a workaround. In case anyone else runs into this:

import mockery from 'mockery'
import * as rn from 'react-native'

mockery.registerMock('react-native', {
  ...rn,
  NativeModules: {
    MyBridge: {
      nativeCall: () => {}
    }
  }
})

This feels a bit dirty though. So leaving this open to wait for some feedback if there's a better way to do it.

RealOrangeOne commented 7 years ago

@chapati23 it's not really clear from your snippets, but remember the first arg of registerMock has to be exactly what's inside require(), not just a path to the file you want to mock. Are you doing this?

chapati23 commented 7 years ago

@RealOrangeOne not sure i understand. in this case i'm mocking the actual react-native npm package so it does work like it's in the snippet