Search code examples
reactjsreact-nativejestjse2e-testingdetox

How to use react-native-i18n in detox[react-native]


I want to test the alert message in detox,and the message use i18n.

const i18n = require("react-native-i18n");

describe("Example", () => {
  beforeEach(async () => {
    await device.reloadReactNative();
  });

  it("should show hello screen after tap", async () => {
    await element(by.id("btnLogin")).tap();
    I18n.t(LocaleKeys.errorMsg_invalidUsername);
    await expect(element(by.text(I18n.t(LocaleKeys.errorMsg_invalidUsername)))).toBeVisible();
    // await expect(element(by.text("Please input the email and password."))).toBeVisible();
  });

});

Run test and get the following error.

Test suite failed to run

/Users/leogeng/Desktop/studentREP/student-app/node_modules/react-native-i18n/index.js:14
export const getLanguages = () => RNI18n.getLanguages();
^^^^^^

SyntaxError: Unexpected token export

  at ScriptTransformer._transformAndBuildScript (../node_modules/jest-runtime/build/script_transformer.js:305:17)
  at Object.<anonymous> (firstTest.spec.js:1:114)
      at Generator.next (<anonymous>)

Then I add the following code for jest:

{
  "preset": "react-native",
  "transformIgnorePatterns": [
    "/node_modules/(?!(react-native(.*)?/|native-base(.*)?/|react-navigation/))"
  ]
}

and get error again:

 Validation Error:

  Module <rootDir>/node_modules/react-native/jest/setup.js in the setupFiles option was not found.

Actually i confirm 'setup,js' exist in node_modules/react-native/jest. I do not know why the error happens, anybody can help me? Thanks


Solution

  • I've had the same problem. I resolve it by importing i18n-js instead of react-native-i18n.

    Because react-native-i18n is not a plain javascript framework, Detox can't import it.

    But react-native-i18n is using i18n-js, so you can access your translations without any problem

    const I18n = require('i18n-js')
    
    // and then you can use it for your tests
    ...
    await element(by.text( I18n.t('hello') )).tap()