React Test Renderer: mocked async function calls don't render mocked return values

Viewed 5

I have a simple component that renders settings and has the following return body.

return (
    <IonContent>
      <IonGrid>
        <IonRow className="ion-justify-content-center">
          <IonCol size="10">
            {/*-- List of all settings available in the game --*/}
            <IonList>
              {settings.map((settingItem: SettingItem, index: number) => (
                <IonItem key={index}>
                  <IonLabel>{settingItem.title}</IonLabel>
                  <IonToggle slot="end"></IonToggle>
                </IonItem>
              ))}
            </IonList>
          </IonCol>
        </IonRow>
      </IonGrid>
    </IonContent>
  );

I use this function and useEffect to render data

const getSettings = async () => {
  const settings = await get("api/settings", token);

  if (settings) {
    setSettings(settings);
  }
};

useEffect(() => {
  getSettings();
}, []);

For the life of me I cannot get my unit test to actually render the mock data to test this component. Note, my actual component works just fine. I believe it to simply be that I am not mocking the get function correctly to display the data.

I have followed several different stack overflows and guides but not yield the data, just empty component, due to what appears to be settings never being returned.

Here is the test:

jest.mock("../../utils/apiHelper/apiHelper", () => {
  return {
    get: jest.fn().mockImplementation(() => [
      {
        title: "test 1",
      },
    ]),
  };
});

test("Displays Setting list", async () => {
  let component;

  act(async () => {
    component = await renderer.create(
      <SettingsList cognitoUser={mockCognitoUser} />
    );
    let tree = component.toJSON();
    expect(tree).toMatchSnapshot();
  });
});

My Snapshot is missing every part of the map functions though, suggesting there is no data to map at all.

Here are the collection of things I have tried so far: https://jestjs.io/docs/mock-functions#mocking-modules

I have tried mocking the return values, mocking implementation to a promise that gets resolved. I have tried a few variation on when and where I act() and not act()ing at all. I have tried asserting in the act outside the act.

What am I missing?

0 Answers
Related