Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 尽管已包装,但未在act错误中包装_Reactjs_Testing_Jestjs_React Testing Library - Fatal编程技术网

Reactjs 尽管已包装,但未在act错误中包装

Reactjs 尽管已包装,但未在act错误中包装,reactjs,testing,jestjs,react-testing-library,Reactjs,Testing,Jestjs,React Testing Library,我正在测试React组件,以验证延迟了setTimeout的回调函数行为,但我收到了下面的错误,尽管我的伪计时器已在act块中触发 错误如下: C:\dev\node\node.exe --require "C:\dev\JetBrains\IntelliJ IDEA 2021.1.1\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-stdin-fix.js" C:\Users\Reph0\

我正在测试React组件,以验证延迟了
setTimeout
的回调函数行为,但我收到了下面的错误,尽管我的伪计时器已在
act
块中触发

错误如下:

C:\dev\node\node.exe --require "C:\dev\JetBrains\IntelliJ IDEA 2021.1.1\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-stdin-fix.js" C:\Users\Reph0\Desktop\my-app\node_modules\react-scripts\bin\react-scripts.js test --colors --reporters "C:\dev\JetBrains\IntelliJ IDEA 2021.1.1\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-reporter.js" --verbose "--testNamePattern=^Timeout component should randomize value until more than 0\.9$" --runTestsByPath C:/Users/Reph0/Desktop/my-app/src/TimeoutComponent.spec.tsx
  console.error
    Warning: An update to TimeoutComponent inside a test was not wrapped in act(...).
    
    When testing, code that causes React state updates should be wrapped into act(...):
    
    act(() => {
      /* fire events that update state */
    });
    /* assert on the output */
    
    This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
        at TimeoutComponent (C:\Users\Reph0\Desktop\my-app\src\TimeoutComponent.tsx:8:35)
组件

import * as React from "react";

interface Props {
  getValue: () => Promise<number>;
}

const TimeoutComponent: React.FC<Props> = (props) => {
  const [value, setValue] = React.useState<number>(0);

  React.useEffect(() => {
    if (value < 0.9) {
      const timeoutId = setTimeout(() => props.getValue().then(setValue), 300);
      return () => {
        clearTimeout(timeoutId);
      };
    }
  }, [value]);

  return (
    <>
      <p>
        Value: <span id="value">{value}</span>
      </p>
    </>
  );
};

export default TimeoutComponent;
下面是我的codesandbox的示例,但似乎
jest.runAllTimers()
在那里不起作用


如果有人能帮忙,我将不胜感激:)

发生错误是因为测试过程中状态发生了变化。我们可以等待状态更改,然后再进行断言

对于您的情况,我们可以等待不包含0.6的内容(0.92之后状态不会更改),并确定getValue之前是否被调用了6次

it(“应该随机化值直到超过0.9”,异步()=>{
getValue
.mockResolvedValue一次(0.1)
.mockResolvedValue一次(0.2)
.mockResolvedValue一次(0.3)
.mockResolvedValue一次(0.4)
.mockResolvedValue一次(0.7)
.mockResolvedValue一次(0.92)
.mockResolvedValue一次(0.6);
const result=render();
试一试{
jest.runAllTimers();
//等待内容包含0.6
//将永远不会显示超时为0.6;以及
//会去抓,最后拦住
等待等待(()=>{
result.getByText(/0.6/)
})
}捕获(e){
log(“等待0.6出现超时:”,e.message)
}最后{
//获取内容中超时前错误的最新值,必须为0.92
expect(result.container.getElementsByTagName(“span”)[0].innerHTML.toEqual(“0.92”);
//get在超时错误之前调用getValue的时间数,必须为6
expect(getValue).toBeCalledTimes(6);
}
});
waitFor
的参考:


我的回答能帮你吗?如果没有,您能提供更多详细信息吗?谢谢您的帮助@MicFung!只要有时间尝试一下就好了!
import { render } from "@testing-library/react";
import React from "react";
import { act } from "react-dom/test-utils";
import TimeoutComponent from "./TimeoutComponent";

const getValue = jest.fn();

describe("Timeout component", () => {
  beforeEach(() => {
    jest.resetAllMocks();
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.useRealTimers();
  });

  it("should randomize value until more than 0.9", () => {
    getValue
      .mockResolvedValueOnce(0.1)
      .mockResolvedValueOnce(0.2)
      .mockResolvedValueOnce(0.3)
      .mockResolvedValueOnce(0.4)
      .mockResolvedValueOnce(0.7)
      .mockResolvedValueOnce(0.92)
      .mockResolvedValueOnce(0.6);

    render(<TimeoutComponent getValue={getValue} />);

    act(() => {
      jest.runAllTimers();
    });

    expect(getValue).toBeCalledTimes(6);
  });
});
{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}