[有状态组件中Text元素的测试内容

问题描述 投票:0回答:1

我正在使用react-native-testing-library。我的组件很简单:

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();
  });

我可以确认是否正确侦听了函数information(),但debug(Logo)仍显示具有空字符串的Text元素。

react-native
1个回答
1
投票

如果监视正确,则可以尝试此操作。我鼓励您使用testID道具作为组件

  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中移动您的信息咨询电话>

© www.soinside.com 2019 - 2024. All rights reserved.