【问题标题】:Jest async componentDidMount acceptance testJest 异步 componentDidMount 验收测试
【发布时间】:2020-03-15 06:41:16
【问题描述】:

我的组件如下:

export default class Link extends React.Component {
  state = { url: "" };

  async componentDidMount() {
    const result = await MyUrlService.getUrl(this.props.urlId);
    this.setState({
      url: result
    });
  }

  render() {
    return (
      this.state.url && (
        <a href={this.state.url}>
          {this.props.text}
        </a>
      )
    );
  }
}

我已经对Link.jsxMyUrlService.js 进行了单元测试,并用测试覆盖了它们(我应该说是绿色!)。

但是,我想进行验收测试以检测我的 Link 组件在 componentDidMount 之后,来自 MyUrlService.getUrl 的响应在 href 属性中。

无论如何,在async componentDidMount 中设置状态后,我一直无法等待组件的重新渲染。
我试过刷新承诺,安装然后刷新承诺,安装,等待安装,都没有运气。

我已经能够成功使用enzyme-async-helpers,但是挂钩到状态似乎不是正确的做法。

这是验收测试的规范文件

import React from "react";
import { shallow, mount } from "enzyme";
import Link from "../../src/components/Link";

describe("link component", () => {
    describe("given valid url Id", () => {
      const flushPromises = () => new Promise(resolve => setImmediate(resolve));

      const mountAndFlush = async (urlId) => {
        const wrapper = mount(<Link urlId={urlId} text={"whatever text} />);
        await flushPromises();
        return wrapper;
      };
      it("should include url from url service", async () => {
        const component = await mountAndFlush("main-landing-page");

        // const component = mount(<Link mpvId="standardBusinessCards" linkType="product" />);
        expect(component.find("a").props().href).toEqual("/landing-page/main");
      });
    });
  });
});

【问题讨论】:

  • 你是模拟 MyUrlService.getUrl 还是使用真正的 API 调用?
  • 因为是验收测试,所以我不 mock 任何东西,所以我使用真正的 API 调用
  • 实际上来自enzyme-async-helperswaitForElement 看起来对我来说是正确的选择。你是如何尝试使用它的?
  • 使用enzyme-async-helpers 确实通过了绿色测试,但我希望酶有更好的测试方法
  • 不,酶没有像 waitForElement 这样的东西,当你模拟一切异步时,它是用于单元测试的库

标签: reactjs jestjs acceptance-testing


【解决方案1】:

在返回包装器之前,您应该更新包装器 (wrapper.update();)。

替换

await flushPromises();
return wrapper;

await flushPromises();
wrapper.update();
return wrapper;

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2018-12-23
    • 2019-06-25
    • 2018-08-31
    • 2016-11-13
    • 1970-01-01
    • 2020-02-12
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多