ghbutton / react-native-simple-crypto

A simpler React-Native crypto library
https://www.npmjs.com/package/react-native-simple-crypto
MIT License
42 stars 25 forks source link

Jest Mock #35

Open pke opened 3 years ago

pke commented 3 years ago

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.

ghbutton commented 3 years ago

I am unsure