笑话异步组件DidMount验收测试

时间:2019-11-19 16:56:42

标签: reactjs jestjs acceptance-testing

我的组件如下:

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");
      });
    });
  });
});

1 个答案:

答案 0 :(得分:0)

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

替换

await flushPromises();
return wrapper;

使用

await flushPromises();
wrapper.update();
return wrapper;
相关问题