【发布时间】: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.jsx 和MyUrlService.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-helpers的waitForElement 看起来对我来说是正确的选择。你是如何尝试使用它的? -
使用
enzyme-async-helpers确实通过了绿色测试,但我希望酶有更好的测试方法 -
不,酶没有像
waitForElement这样的东西,当你模拟一切异步时,它是用于单元测试的库
标签: reactjs jestjs acceptance-testing