тестировать содержимое текстового элемента в компоненте с отслеживанием состояния - PullRequest
0 голосов
/ 07 мая 2020

Я использую библиотеку response-native-testing. Мой компонент довольно прост:

import React, {Component} from 'react';
import {Text, View} from 'react-native';
import {information} from './core/information';

export default class Logo extends Component {
  constructor() {
    super();
    this.state = {
      name: ''
    };
    information()
      .then((details) => {
        this.setState({
          name: details['name']
        });
      })
      .catch((e) => {
        console.log(e);
      });
  }

  render() {
    return (
      <>
        <View>

          <Text>{this.state.name}</Text>

        </View>
      </>
    );
  }
}

Я хочу убедиться, что он содержит правильный контент. Я пробовал следующее, но это не удалось:

import * as info from "./lib/information";

it('displays correct text', () => {
    const spy = jest.spyOn(info, 'information')
    const data = {'name':'name'}
    spy.mockResolvedValue(Promise.resolve(data));

    const {queryByText, debug} = render(<Logo />);
    expect(queryByText(data.name)).not.toBeNull();

    expect(spy).toHaveBeenCalled();
  });

Я могу подтвердить, что информация о функции () отслеживалась правильно, но все еще отладка (Lo go) показывает текстовый элемент с пустой строкой.

1 Ответ

1 голос
/ 07 мая 2020

Если он правильно шпионит, вы можете попробовать это. Я рекомендую вам использовать testID props для компонентов

  render() {
    return (
      <>
        <View>

          <Text testID="logo-text">{this.state.name}</Text>

        </View>
      </>
    );
  }
import * as info from "./lib/information";
import { waitForElement, render } from "react-native-testing-library";

it('displays correct text', () => {
    const spy = jest.spyOn(info, 'information')
    const data = {'name':'name'}
    //this is already resolving the value, no need for the promise
    spy.mockResolvedValue(data);

    const {getByTestId, debug} = render(<Logo />);
    //You better wait for the spy being called first and then checking
    expect(spy).toHaveBeenCalled();

    //Spy function involves a state update, wait for it to be updated
    await waitForElement(() => getByTestId("logo-text"));
    expect(getByTestId("logo-text").props.children).toEqual(data.name);
  });

Кроме того, вы должны переместить свой информационный вызов в componentDidMount

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...