【问题标题】:Jest testing: How do I correctly write expect assertions witin a setTimeout?开玩笑测试:如何在 setTimeout 中正确编写期望断言?
【发布时间】:2021-08-03 18:05:51
【问题描述】:

我想 JEST 测试一个 React 组件,它在渲染状态之前和之后都会在超时后更新状态。 expect() 断言在 test() 中工作正常,但在 SetTimeout 回调中使用时会中断。在 setTimeout 回调中未定义期望的错误状态。

我在这里创建了一个沙盒: https://codesandbox.io/s/jest-delayed-render-test-j5b7l

SetTimeout 后的简单组件更新状态。


// delayed.js
import { useEffect, useState } from "react";

export const Delayed = () => {
  let [value, setValue] = useState("foo");

  useEffect(() => {
    let handle = setTimeout(() => {
      setValue("bar");
    }, 3000);

    return () => {
      clearTimeout(handle);
    };
  }, []);

  return (
    <>
      <h1>MyPromise</h1>
      <p>value = {value}</p>
    </>
  );
};


简单的测试断言组件之前和更新超时

// delayed.test.js

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import { Delayed } from "./delayed";

let container = null;
beforeEach(() => {
  container = document.createElement("div");
  document.body.appendChild(container);
});
afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

it("checks initial value", async () => {
  await act(async () => {
    render(<Delayed />, container);
  });
  expect(container.textContent).toContain("foo");
});

it("checks final value", async () => {
  await act(async () => {
    render(<Delayed />, container);
  });

  setTimeout(() => {
    // this doesnt get executed!
    // error: expect is not defined
    expect(container.textContent).toContain("1234");
  }, 2000);
});

【问题讨论】:

    标签: reactjs asynchronous jestjs settimeout


    【解决方案1】:

    这很容易解决,作为测试的参数传入。

    it("checks final value", async (done) => {
      await act(async () => {
        render(<Delayed />, container);
      });
    
      setTimeout(() => {
        expect(container.textContent).toContain("bar");
        done();
      }, 3000);
    });
    

    如此处所述:

    https://www.pluralsight.com/guides/test-asynchronous-code-jest

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2021-06-04
      • 2020-05-11
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2020-07-20
      相关资源
      最近更新 更多