首页 > 解决方案 > 如何让 Jest 等待状态更新 - React / Jest / Enzyme

问题描述

我有一个简单的程序,可以在单击按钮时更改 textField 的 helperText。

在 Jest 中,我正在模拟按钮按下,然后我想验证帮助文本是否已更改。目前,我只是在单击之前和之后控制台记录文本字段,但在这两种情况下,它都说值是“”。单击执行后,我希望它是“用户名不得包含任何特殊字符”。

笑话/酶测试:

import React from "react";
import RegistrationPage from "../pages/registration";
import { configure, mount } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { act } from "react-dom/test-utils";
import TextField from "@material-ui/core/TextField";

configure({ adapter: new Adapter() });

describe("App", () => {
  it("renders without crashing", () => {
    let wrapper;
    act(() => {
      wrapper = mount(<RegistrationPage />);

      console.log("BEFORE CLICK");
      console.log(wrapper.find(TextField).first().props());

      wrapper.find("#submitRegForm").first().props().onClick();
    });

    console.log("AFTER CLICK");
    console.log(wrapper.find(TextField).first().props());

  });
});

React 看起来像这样:

const onSubmitHandler = ()=>{
 setDisplayName({ 
 ...displayName, 
 helperText: "Username must not contain any special characters",
 error: true
});
}

.
.
.

<TextField {...props} size="small" fullWidth variant="outlined" />

<Button 
 variant="contained"
 color="primary"
 fullWidth
 onClick={onSubmitHandler}
 id="submitRegForm">
 Finish
</Button>

标签: reactjsjestjsenzyme

解决方案


也许你是一种更规范的方式,但我个人只是使​​用

it('...', (done) => {
    //simulating some async functions

    setTimeout(() => {
        expect...

        done();
    });
}

推荐阅读