Colin Steel
Colin Steel

Reputation: 11

React Native Jest testing

We have a React Native app, and have trouble in Jest testing this:

import React from 'react';
import { render } from '@testing-library/react-native';
import MyScreen from '../../../../../src/screens/MyScreen/index';
import Provider from '../../../../__helpers__/Provider';
import { t } from 'core/utils';
import '@testing-library/jest-dom';

jest.mock('@react-navigation/native', () => {
  return {
    ...jest.requireActual('@react-navigation/native'),
    useNavigation: () => ({
      navigate: jest.fn(),
    }),
  };
});

jest.mock('@react-navigation/core', () => {
  return {
    ...jest.requireActual('@react-navigation/core'),
    useFocusEffect: () => ({
      navigate: jest.fn(),
    }),
  };
});

describe('<AddEditSchedulable />', () => {
  it('tests a button is disabled', () => {
    const myProperty = {
      myData: 'myData'
    };

    const myRender = render(
      Provider(() => <MyScreen myProperty={myProperty} />),
    );

    const button = myRender.getByText(t('common.buttons.save')); // Returns a complex "_fiber" object.
    expect(button).toBeDisabled(); // Expects an HTML element.
  });
});

The button returned by getByText contains an object we dont understand containing lots of "_fiber" objects. From this I think we need to get HTML elements to correctly use the toBeDisabled function, but this is React Native and I dont think it uses HTML elements under the hood.

So can we either, get HTML elements from React Native, or can we get functions that understand React Native elements that have the functionality we need (at least accessing properties, ie "disabled")?

We are in circles because standard React seems very different to React Native in Jest tests.

Upvotes: 1

Views: 674

Answers (1)

user275564
user275564

Reputation: 318

The library @testing-library/jest-dom is meant only for @testing-library/react. Since you are using React Native, the custom matcher toBeDisabled() doesn't understand the element. The import for react native is below.

import '@testing-library/jest-native/extend-expect';

Remove the import and remove it from the project.

import '@testing-library/jest-dom';

Also, please make sure this returns a react native component.

 Provider(() => <MyScreen myProperty={myProperty} />),

Upvotes: 2

Related Questions