【问题标题】:Make jest/enzyme test wait for context让笑话/酶测试等待上下文
【发布时间】:2020-06-19 03:08:41
【问题描述】:

我很难进行等待上下文新状态的测试。 这是一个简单的应用程序,它在获取用户之前显示加载程序:

(我知道所有代码都不是让应用程序执行其功能所必需的,但它更多地反映了我在实际项目中的实现方式)

export const Greeting: React.FC<{}> = () => {
  const { loading, user } = useUserContext();

  return (
    <div>
      {loading ? (
        <CircularProgress />
      ) : (
        <h1>
          Hello {user.firstname} {user.lastname}
        </h1>
      )}
    </div>
  );
};

这是测试:

import React from "react";
import Adapter from "enzyme-adapter-react-16";
import Enzyme, { mount } from "enzyme";
import { Greeting } from "./Greeting";
import { UserContextProvider } from "./UserContext";

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

describe("Test of <Greeting />", () => {
  it(">>>> should show spinner on loading = true", () => {
    const wrapper = mount(<Greeting />);
    expect(wrapper.find("ForwardRef(CircularProgress)").exists()).toEqual(true);
  });
  it(">>>> should show greeting on loading = false", async () => {
    const wrapper = mount(
      <UserContextProvider>
        <Greeting />
      </UserContextProvider>
    );
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve(wrapper);
      }, 5000);
    });
    promise.then((res: Enzyme.ReactWrapper<any>) => {
      console.log(res.debug());
      expect(res.find("h1").text()).toEqual("Hello Bob Testman");
    });
  });
});

codesandbox 的链接: https://codesandbox.io/embed/modern-sea-tx3ro?fontsize=14&hidenavigation=1&theme=dark

关于如何解决这个问题的任何想法?

更新 感谢@Noix,这完美无缺

it(">>>> should show greeting on loading = false", async () => {
const wrapper = mount(
  <UserContextProvider>
    <Greeting />
  </UserContextProvider>
);
const promise = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      wrapper.update();
      resolve(wrapper);
    }, 3000);
  });
};
return promise().then((res: Enzyme.ReactWrapper<any>) => {
  console.log(res.debug());
  expect(res.find("h1").text()).toEqual("Hello Bob Testman");
});

【问题讨论】:

    标签: reactjs jestjs enzyme react-context


    【解决方案1】:

    我相信您遇到了麻烦,因为 Jest 在您的承诺完成之前结束了测试。尝试在“promise.then”之前添加语句“return”,以便 Jest 能够在结束测试之前等待您的承诺结束。

    据此:

    https://jestjs.io/docs/en/asynchronous.html

    Jest 不等待回调返回,除非:

    选项 1:您将 done 作为参数添加到您的函数“it”,因此测试仅在您调用函数 done 时才解析(在这种情况下,您需要使用 try catch 以确保始终调用 done)

    选项 2:你使用一个承诺,这是最简单的,但永远不要忘记返回你的承诺 :)

    选项 3:您可以使用语句“await”作为您的承诺,但是您必须在您的“it”函数上使用关键字 async

    因此,在您的情况下,您可以在您的承诺上放置一个 await 以等待它结束,或者只是返回您的承诺。我希望这会有所帮助。

    干杯:)

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 2018-06-21
      • 1970-01-01
      • 2018-12-19
      • 2021-09-07
      • 2018-03-23
      • 2020-06-14
      • 1970-01-01
      • 2017-08-18
      相关资源
      最近更新 更多