How can i cover the missing lines on this test with @testing-library/react-native and jest AccessDoorsModal

17 Views Asked by At

I'd like to cover 100% of the code, but I don't know how to test the missing lines.

I wasn't able to understand and learn how to achieve 100% coverage of the tests of this component.

I've tried to create a test to get the flatList by the id, and I've got it, but when i tried to get the items of the flatList i got an error AccessDoorsModal › a Unable to find an element with testID: access-doors-list-item

Any idea how to achieve this? Thanks in advance!

This is my component:

import React, { useCallback, useMemo } from 'react';
import {
  FlatList,
  Modal,
  StatusBar,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  View,
} from 'react-native';

import { ThemeConfig } from 'tailwindcss/types/config';

import useAccessSelectedStore from '../../stores/accessSelected';
import useOpenMapNavigator from '../../hooks/useOpenMapNavigator';
import { ch } from '../../utils/DimensionsStyles';
import { theme } from '../../../tailwind.config';

type AccessDoorsModalProps = {
  isAccessDoorsModalVisible: boolean;
  setIsAccessDoorsModalVisible: (v: boolean) => void;
};

function AccessDoorsModal({
  isAccessDoorsModalVisible,
  setIsAccessDoorsModalVisible,
}: AccessDoorsModalProps) {
  const { accessSelected, setAccessSelected } = useAccessSelectedStore(
    state => state,
  );
  const { handleOpenMap } = useOpenMapNavigator();
  const { colors } = useMemo(() => theme?.extend as ThemeConfig, [theme]);

  const filterAccessDoors = useCallback(() => {
    if (accessSelected?.openNavigation) {
      // if openNavigation is true, show all access doors
      return accessSelected?.accessDoors;
    }
    // if openNavigation is false, show only access doors with iot
    return accessSelected?.accessDoors?.filter(item => item.hasIot === true);
  }, [accessSelected]);

  const handleHeight = useCallback(() => {
    const accessDoorsLength = filterAccessDoors()?.length || 0;
    return accessDoorsLength * 60;
  }, []);

  return (
    <>
      <StatusBar
        translucent
        barStyle="dark-content"
        backgroundColor={colors['overlay']}
      />
      <Modal
        testID="access-doors-modal"
        animationType="fade"
        transparent
        visible={isAccessDoorsModalVisible}
        onRequestClose={() => {
          setIsAccessDoorsModalVisible(false);
        }}
      >
        <TouchableOpacity
          testID="close-button"
          className="flex-1 justify-center items-center bg-overlay"
          activeOpacity={1}
          onPress={() => setIsAccessDoorsModalVisible(false)}
        >
          <TouchableWithoutFeedback>
            <View className="w-[94%] px-5 py-5 rounded-lg items-center shadow-md bg-secondary">
              <Text className="text-lg font-bold text-primary mb-4 font-rubik_bold">
                Seleccione una puerta de acceso
              </Text>
              <View
                style={{
                  height: ch(handleHeight()),
                  width: '85%',
                }}
              >
                <FlatList
                  contentContainerStyle={{
                    paddingTop: 10,
                  }}
                  testID="access-doors-list"
                  data={filterAccessDoors() ?? []}
                  keyExtractor={item => item.id}
                  extraData={filterAccessDoors() ?? []}
                  keyboardShouldPersistTaps="always"
                  scrollEnabled
                  initialScrollIndex={0}
                  renderItem={({ item }) => (
                    <TouchableOpacity
                      testID="access-doors-list-item"
                      className="mb-5"
                      onPress={() => {
                        setAccessSelected({
                          ...accessSelected,
                          doorSelected: item,
                          showOpenDoorModal: item.hasIot,
                          showAccessDoorsModal: false,
                        });
                        if (accessSelected?.openNavigation) {
                          setTimeout(() => {
                            handleOpenMap({
                              start: undefined,
                              end: item.address,
                              travelType: 'drive',
                            });
                          }, 1000);
                        }
                      }}
                    >
                      <Text className="text-sm font-rubik_regular text-text_custom_gray">
                        {item.address
                          ?.substring(0, 37)
                          .concat(item.address?.length > 37 ? '...' : '')}
                      </Text>
                    </TouchableOpacity>
                  )}
                />
              </View>
            </View>
          </TouchableWithoutFeedback>
        </TouchableOpacity>
      </Modal>
    </>
  );
}

export default AccessDoorsModal;

This is my tests:

import { render, fireEvent } from '@testing-library/react-native';
import AccessDoorsModal from '..';

describe('AccessDoorsModal', () => {
  it('renders modal when isAccessDoorsModalVisible is true', () => {
    const setIsAccessDoorsModalVisible = jest.fn();
    const { getByTestId } = render(
      <AccessDoorsModal
        isAccessDoorsModalVisible
        setIsAccessDoorsModalVisible={setIsAccessDoorsModalVisible}
      />,
    );
    const modal = getByTestId('access-doors-modal');
    expect(modal).toBeDefined();
  });

  it('calls setIsAccessDoorsModalVisible with false when modal is closed', () => {
    const setIsAccessDoorsModalVisible = jest.fn();
    const { getByTestId } = render(
      <AccessDoorsModal
        isAccessDoorsModalVisible
        setIsAccessDoorsModalVisible={setIsAccessDoorsModalVisible}
      />,
    );
    const closeButton = getByTestId('close-button');
    fireEvent.press(closeButton);
    expect(setIsAccessDoorsModalVisible).toHaveBeenCalledWith(false);
  });

  it('calls setIsAccessDoorsModalVisible with false when backdrop is pressed', () => {
    const setIsAccessDoorsModalVisible = jest.fn();
    const { getByTestId } = render(
      <AccessDoorsModal
        isAccessDoorsModalVisible
        setIsAccessDoorsModalVisible={setIsAccessDoorsModalVisible}
      />,
    );
    const backdrop = getByTestId('close-button');
    fireEvent.press(backdrop);
    expect(setIsAccessDoorsModalVisible).toHaveBeenCalledWith(false);
  });

  it('should call onRequestClose when modal is closed', () => {
    const setIsAccessDoorsModalVisible = jest.fn();
    const { getByTestId } = render(
      <AccessDoorsModal
        isAccessDoorsModalVisible
        setIsAccessDoorsModalVisible={setIsAccessDoorsModalVisible}
      />,
    );
    const modal = getByTestId('access-doors-modal');
    fireEvent(modal, 'requestClose');
    expect(setIsAccessDoorsModalVisible).toHaveBeenCalledWith(false);
  });

  it('should render the access doors list', () => {
    const setIsAccessDoorsModalVisible = jest.fn();
    const { getByTestId } = render(
      <AccessDoorsModal
        isAccessDoorsModalVisible
        setIsAccessDoorsModalVisible={setIsAccessDoorsModalVisible}
      />,
    );
    const accessDoorsList = getByTestId('access-doors-list');
    expect(accessDoorsList).toBeDefined();
  });
});
0

There are 0 best solutions below