react-native - 在有状态组件中测试 Text 元素的内容
问题描述
我正在使用 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 元素。
解决方案
如果它是正确的间谍,你可以试试这个。我鼓励你使用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
推荐阅读
- django - 如何在 Django 中限制 18 岁以下用户的表单验证
- computer-vision - 是否实施了任何用于行人检测或行人跟踪的光流算法?
- php - 使用 ajax 发送的数据有效,但 $_POST 和 GET 在 php 后端文件中不起作用
- selenium - Selenium,如何阻止来自 chrome 的位置“警报”?
- database - 如何规范化具有外键的表
- reactjs - 如何使用 useEffect 正确生成 html 元素?
- audio - 如何删除 ffmpeg 转换生成的 .mp3 文件开头的零填充?
- sql - 外键返回 null
- symfony - 我的 Webpack Encore 只加载文件名,不加载文件内容?
- asp.net-core - Dart 上传文件到 asp.net Core