Как проверить, как setState меняет вывод моего рендера в React? - PullRequest
0 голосов
/ 21 января 2020

У меня есть реагирующий комп без состояния, который отображает список тегов; основываясь на длине списка, он отображает его полностью ИЛИ обрезает его и отображает кнопку «ShowMore»;

все работает нормально; Мне нужно создать модульные тесты для этого, но я не смог этого сделать.

вот мой код:

const yPositionBreakpoint = 120
const initialMaxIndex = 9999

/**
 * Display the list of events of selected customer
 * if list is long and takes more than 3 rows,
 * shows a "More" button and hides the rest of the list to be displayed with that button
 *
 * @param {Array} events to display
 */
const Lists = ({ events }) => {
  const [list, setList] = useState(events)
  const [isListCropped, setIsListCropped] = useState(false)
  const [isListExpanded, setIsListExpanded] = useState(false)
  // control variables; useRef instead of useState to reduce renders
  const evaluatedIndexRef = useRef(-1)
  const lowestOffBoundsIndexRef = useRef(initialMaxIndex)

  // Evaluates position of list element to fulfill requirement of 3 rows only
  const checkItemPosition = (layout, index) => {
    evaluatedIndexRef.current = evaluatedIndexRef.current + 1
    // if position of element is lower than breakpoint and element index is lower than current lowest, then store index
    if (
      layout.y > yPositionBreakpoint &&
      index < lowestOffBoundsIndexRef.current
    ) {
      lowestOffBoundsIndexRef.current = index
    }
    // all elements have been evaluated and there is at least one element lower than breakpoint, then crop list
    if (
      evaluatedIndexRef.current === events.length - 1 &&
      lowestOffBoundsIndexRef.current !== initialMaxIndex
    ) {
      cropList()
    }
  }

  // crops list in the lowest index that exceeds the breakpoint
  const cropList = () => ((setIsListCropped(true), setList(list.slice(0, lowestOffBoundsIndexRef.current - 1))))

  // shows elements previously cropped, triggered by 'showMoreButton'
  const expandList = () => ((setIsListExpanded(true), setList(events)))

  return (
      <View style={styles.container}>
        {list.map((el, index) => (
          <Text
            style={styles.tag}
            onLayout={event =>
              !isListCropped &&
              checkItemPosition(event.nativeEvent.layout, index)
            }
          >
            {el}
          </Text>
        ))}
        {isListCropped && !isListExpanded && (
          <Button
            testID='showMoreButton'
            label='More'
            variant='text'
            onPress={expandList}
          />
        )}
      </View>
  )
}

Я хочу написать такой тест:

const wrapper = mount(<Lists events={longList} />)
it('THEN should display the more button', () => {
   expect(wrapper.find({ testID: 'showMoreButton' }).exists()).toBeTruthy()
})

const wrapper = mount(<Lists events={shortList} />)
it('THEN should NOT display the more button', () => {
   expect(wrapper.find({ testID: 'showMoreButton' }).exists()).toBeFalsy()
})

Но я не смог этого сделать, всегда получал первый результат рендеринга в оболочке, таким образом, полный список событий

Как мне этого добиться?

...