首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试有状态组件中的文本元素的内容

测试有状态组件中的文本元素的内容
EN

Stack Overflow用户
提问于 2020-05-07 20:08:05
回答 1查看 87关注 0票数 0

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

代码语言:javascript
复制
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>
      </>
    );
  }
}

我想确保包含正确的内容。我尝试了以下方法,但失败了:

代码语言:javascript
复制
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)仍然显示为空字符串的文本元素。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-07 22:10:45

如果它是正确的间谍,你可以试试这个。我鼓励您使用组件的testID属性

代码语言:javascript
复制
  render() {
    return (
      <>
        <View>

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

        </View>
      </>
    );
  }
代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61657416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档