如何使Jest等待状态更新-React / Jest / Enzyme

时间:2020-08-19 15:06:22

标签: reactjs jestjs enzyme

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

在Jest中,我正在模拟按钮的按下,然后我想验证帮助程序文本是否已更改。当前,我只是在单击前后在console.logging文本字段,但是在两种情况下,它都表示值为“”。在执行点击后,我希望它是“用户名不能包含任何特殊字符”。

开玩笑/酶测试:

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>

1 个答案:

答案 0 :(得分:1)

也许您是一种更规范的方法,但是我个人而言,只需使用

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

    setTimeout(() => {
        expect...

        done();
    });
}
相关问题