maxkomarychev / react-native-ultimate-config

Config that works
MIT License
261 stars 31 forks source link

Jest: Mock the library react-native-ultimate-config #55

Closed aymkin closed 3 years ago

aymkin commented 3 years ago

One of the files has (translation setup) imports the RNUC. And the selection of the right translations is heavily relies on .env variables. During the runtime, it resolves properly:

import config from 'react-native-ultimate-config';

console.log('--- config --- ', config);

// output
// --- config ---  {
// APP_NAME: "fooBar",
// BUNDLE_ID: "com.foo.bar
// ....
// }

But if I run the test

yarn jest app/component/Component.test.tsx

the output is

--- config ---  {}

That means I need to mock the library somehow, and I did not found the proper instructions in README

Please guide me on how to implement that.

Thank you a lot

@isilher @maxkomarychev

isilher commented 3 years ago

Hi @aymkin! For jest, simply treat it as a native dependency and mock it. For example:

jest.doMock('react-native-ultimate-config', () => {
  return {
    APP_NAME: "fooBar",
    BUNDLE_ID: "com.foo.bar",
  }
})
maxkomarychev commented 3 years ago

Hi @aymkin ,

there's nothing special about mocking this library. It can be mocked with jets's module mocks. Something as simple as:

jest.mock('react-native-ultimate-config', () => ({
    APP_NAME: "fooBar",
    BUNDLE_ID: "com.foo.bar",
}))

if you got more troubles with these - please consider sharing a reproducible example. thank you.

aymkin commented 3 years ago

What I actually did

const ReactNativeUltimateConfig: ConfigVariables = { APP_NAME: 'foo', APP_VERSION: 'bar', BUNDLE_ID: 'baz', };



That is it, PROFIT! 
maxkomarychev commented 3 years ago

To be honest I'm slightly confused with how this can work at all.

Seems like some typescript definitions are not 100% accurate.

There is no exported variable ConfigVariables - there is only one default export: https://github.com/maxkomarychev/react-native-ultimate-config/blob/51e133ee0f45f157fe82475a57c9ff0b7dd79fac/index.js#L1-L6

and the default export should be mocked, not ConfigVariables. that said I have never tried to mock it myself, I need to try it.

aymkin commented 3 years ago

There are ConfigVaribles in node_modules/react-native-ultimate-config/index.d.ts

maxkomarychev commented 3 years ago

yes, that's the problem - this not a variable that is exported. it's rather ephemeral variable which exists only in typescript but no in js

maxkomarychev commented 3 years ago

I added example of mock here https://github.com/maxkomarychev/react-native-ultimate-config/blob/master/packages/example/__tests__/App-test.js