jeudi 5 décembre 2019

Using Jest Mock API Calls to SetState

I have an API call which runs whenever a certain component mounts. If this API call is successful the response data is used to update the state of one of my React Hooks.

Here is a simplified version of the API call:

const getOrg =() => {
  axios.get(URL, config)
    .then(response => response.data)
    .then(data => {
       setOrgTitle(data.name)
    }
}

Basically the API is triggered and my setOrgTitle hook is updated from the response.

const [orgTitle, setOrgTitle] = useState("");

Now in my return statement I am displaying the value of orgTitle:

<h1 className={styles.titleText} id="document-folders-h1">
  {orgTitle} Folders
</h1>

Alright, so the component is pretty simple. When I am trying to test things my two ideas were to either set the initial orgTitle hook state in my test or to mock the API. After some research I decided mocking the API was the way to go.

So I have a mockAxios component:

const mockAxios = {
  get: jest.fn(() => Promise.resolve({ data: {} }))
};

module.exports = mockAxios;

And my test file:

import mockAxios from "../../mockTests/DocumentFoldersMock";

it("fetches results for getAdminOrg", () => {
  mockAxios.get.mockImplementationOnce(() =>
    Promise.resolve({
      uuid: "0e89d",
      name: "GETtest",
      slug: "gettest",
      size: 321,
      seats: 123
    })
  );
  const wrapper = mount(
    <AppProviders>
      <DocumentFolders />
    </AppProviders>
  );
  const orgTitle = wrapper.find("#document-folders-h1");
  expect(orgTitle.text()).toContain("GETtest Folders");
});

I am mocking the response data, however I am not sure to run the setOrgTitle function which is called in the .then of my actual axios call. How can I do this from my mock axios call using my mock response?

Aucun commentaire:

Enregistrer un commentaire