mercredi 5 octobre 2016

Mocking a Native Module when testing with Jest

I'm trying to write tests for my application, but I currently get the following error:

● Test suite failed to run

TypeError: Cannot read property 'language' of undefined

  at Object.<anonymous> (node_modules/react-native-localization/LocalizedStrings.js:17:35)

It seems that the error is caused by this line in React-Native-Localization that retrieves the device's locale:

var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');

The package is used in a wrapper that returns translated strings to the component, so the package isn't called directly. It looks something like this:

Component:

import wrapper from '../wrapper'

class component extends Component {
  render() {
    return(
      <Text>{wrapper.getString(key)}</Text>
    );
  }      

  // ...
}

Wrapper:

import LocalizedStrings from 'react-native-localization'

class wrapper {

  constructor() {
    this.translations = new LocalizedStrings( ... );
  }

  getString(key) {
    return eval(`this.translations.${key}`);
  }

  // ...
}

React-Native-Localization:

var localization = require('react-native').NativeModules.ReactLocalization;
var interfaceLanguage = localization.language.replace(/_/g,'-');

class LocalizedStrings {
  // ...
}

The localization variable is set outside of the class and trying to set the variable like this doesn't work for me and returns the same error:

jest.mock('react-native-localization', () => {
  // This doesn't work
  const localization = { language: "en-US" }

  // This doesn't work either, because it hits the var initialization
  const rnl = require.requireActual('react-native-localization')
  rnl.localization = { language: "en-US" }

  // ...
})

Does anyone know how to mock this react native module?

Aucun commentaire:

Enregistrer un commentaire