react-native-simple-crypto icon indicating copy to clipboard operation
react-native-simple-crypto copied to clipboard

Jest Mock

Open pke opened this issue 4 years ago • 1 comments

I am somehow unable to write a proper mock for the library. I though to mock all native calls using node-forge JS calls. I know it will not properly test this native module (we would need detox tests that run natively on the device-emu) but just so I have test coverage of my decrypting code that uses RNSC in some places.

So what I tried in my jest test file is this:

import { NativeModules } from "react-native"

import { md, pki, util } from "node-forge"

NativeModules.RNSCSha = {
  shaUtf8(data: string, algorithm: string) {
    return md.sha512.create().update(data).digest().toHex()
  },
  shaBase64(data: string, algorithm: string) {
    return Promise.resolve(md.sha512.create().update(data).digest().toHex())
  },
},
NativeModules.RNSCRsa = {
  decrypt64(data: string, privateKey: string) {
    console.log(data)
    return Promise.resolve(pki.privateKeyFromPem(privateKey).decrypt(util.decode64(data)))
  },
}

But I am still getting

TypeError: Cannot read property 'shaBase64' of undefined

      at SHAWrapper$ (node_modules/react-native-simple-crypto/index.js:77:48)

which is

const result = await NativeModules.RNSCSha.shaBase64(dataBase64, algorithm);

Any idea what could be wrong with my mocks? I also tried jest.mock but it also did not work.

pke avatar Mar 02 '21 02:03 pke

I am unsure

ghbutton avatar Mar 04 '21 03:03 ghbutton