是否可以等待组件渲染? React 测试库/Jest

时间:2021-06-16 14:04:58

标签: react-native jestjs react-testing-library

我有一个组件。它有一个按钮。按下按钮后,我正在使用 setState 函数更改按钮文本(颜色)的样式。当我测试更改的组件时,测试失败,因为更改是异步发生的。我想做一些这里给出的事情 (https://testing-library.com/docs/dom-testing-library/api-async/)

const button = screen.getByRole('button', { name: 'Click Me' })
fireEvent.click(button)
await screen.findByText('Clicked once')
fireEvent.click(button)
await screen.findByText('Clicked twice')

而不是等待文本更改。我想等待文字颜色改变。谢谢

这是我的按钮代码

<Button onPress = {() => {this.setState({state : 1});}}>
<Text style = {style}>Button Text</Text>
</Button>

所以当这个按钮被按下时。状态设置为 1。并在渲染中:

if(this.state.state === 1) style = style1
else style = style2;

但是从日志中可以看出,render 是在测试检查样式后调用的。那么如何在检查字体颜色是否已更改之前等待渲染完成?

这是测试代码

test('The button text style changes after press', () => {
  const {getByText} = render(<Component/>);
  fireEvent.press(getByText('button'));
  expect(getByText('button')).toHaveStyle({
    color : '#ffffff'
  });
})

2 个答案:

答案 0 :(得分:0)

你可以试试

<Text style = {this.state.state === 1 ? style1 : style2}>Button Text</Text>

这将导致始终定义样式。因此,您不必等待 setState 完成。
编辑
您可以使用 setState 函数提供的回调来执行样式测试。

this.setState({
   state : 1
} , () => {
    //this is called only after the state is changed
    //perform your test here
})

答案 1 :(得分:0)

看起来您有一个自定义按钮,而不是本机按钮。我猜你的组件是这样的:

import React from "react";
import {Text, TouchableOpacity, View} from "react-native";

const Button = ({pressHandler, children}) => (
  <TouchableOpacity onPress={pressHandler}>
    {children}
  </TouchableOpacity>
);

const ColorChangingButton = ({text}) => {
  const [color, setColor] = React.useState("red");
  const toggleColor = () => setTimeout(() => 
    setColor(color === "green" ? "red" : "green"), 1000
  );
  return (
    <Button pressHandler={toggleColor}>
      <Text style={{color}}>{text}</Text>
    </Button>
  );
};
export default ColorChangingButton;

如果是这样,您可以使用 waitFor 进行测试here

import React from "react";
import {
  fireEvent, 
  render,
  waitFor,
} from "@testing-library/react-native";
import ColorChangingButton from "../src/components/ColorChangingButton";

it("should change the button's text color", async () => {
  const text = "foobar";
  const {debug, queryByText} = render(<ColorChangingButton text={text} />);
  fireEvent.press(queryByText(text));
  await waitFor(() => {
    expect(queryByText(text)).toHaveStyle({color: "green"});
  });
});

对于具有 rigid semantics for changing colors 且不接受子元素的原生按钮,而是使用 title="foo",对 debug() 的调用表明它扩展为几个嵌套元素。你可以使用

const text = within(queryByRole("button")).queryByText(/./);
expect(text).toHaveStyle({color: "green"});

waitFor 回调中浸入按钮的文本子项并等待它具有所需的颜色。

我在这篇文章中使用了与 React Testing Library: Test if Elements have been mapped/rendered 中所示相同的软件包/版本。