Reputation: 702
My component is the following:
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>
)
);
}
}
I've unit tested Link.jsx
and MyUrlService.js
covering them with tests (green I should say!).
However, I would like to have an acceptance test to detect that my Link component, after componentDidMount
, the response from MyUrlService.getUrl
is in the href
prop.
Anyhow, I haven't been able to await for the re-render of the component after setting the state in async componentDidMount
.
I've tried flushing promises, mounting then flushing promises, mounting, awaiting mounting, all to no luck.
I've been able to successfully use enzyme-async-helpers
, but hooking to the state doesn't seem the right thing to do.
Here's the spec file for the acceptance test
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");
});
});
});
});
Upvotes: 0
Views: 119
Reputation: 54
Before return the wrapper you should update the wrapper (wrapper.update();).
Replace
await flushPromises();
return wrapper;
with
await flushPromises();
wrapper.update();
return wrapper;
Upvotes: 0