I've been working through this problem for a couple days and believe I am close to a solution. I am trying to mock an API call which is triggered in my useEffect
useEffect(() => {
getAdminOrg();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const getAdminOrg = () => {
const token = localStorage.getItem("token");
const URL = `organizations/organizations/`;
let config = {
headers: { Authorization: "JWT " + token }
};
axios
.get(URL, config)
.then(response => {
setOrgTitle(response.data.name);
})
.catch(error => {
if (error.response) {
console.log(error.response);
if (error.response.status === 401) {
props.renewToken();
}
}
});
};
If the setOrgTitle
hook runs I will be able to detect this by a change to a text field. I am trying to test this here:
it("mocks API call", done => {
const wrapper = mount(
<OrganizationDocs />
);
const mock = new MockAdapter(axios);
mock
.onGet(`organizations/organizations/`, {
headers: { Authorization: "JWT1111" }
})
.reply(200, response.data);
setImmediate(() => {
wrapper.update();
expect(findByTestId(wrapper, "org-docs-header").text()).toContain(
organizationsOrganizations[0].name
);
done();
});
});
I am getting unhandled promise rejection warnings when I run my tests. Also when I try to console log the wrapper
I can see that the API call is not using the test header that I am applying so I am pretty certain the API call is not using my mock.
Any help would be appreciated.
Here is the unit test solution only using
jestjs
+enzyme
+react-dom/test-utils
.E.g.
index.ts
:index.spec.ts
:Unit test result with coverage report:
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59379085