mercredi 1 mai 2019

Jest fails on two async tests, succeeds on each separetely

I have a strange issue with my tests. I have a suite that runs couple of async its. It looks like this:

const successData = {
  ...defaultAnswer,
  status: 200,
  data: {
    "address": "Address",
    "date": "Date & time",
  },
};

const failData = {
  ...defaultAnswer,
  status: 500,
  data: {},
};

jest.mock("axios");

describe("Redux translate tests", () => {
  beforeEach(() => {
    store = makeStore();
    dispatch = store.dispatch;
  });

  it("should properly fetch translations", async () => {
    mockedAxios.get.mockResolvedValueOnce({ ...successData });
    expect(store.getState().translations.getIn(["en", "generic"])).toBeUndefined();

    await dispatch(fetchTranslations({ domain: "generic", language: "en" }));
    const current = store.getState().translations;
    console.log(store.getState().translations.toJS());

    expect(axios.get as jest.Mock).toHaveBeenCalled();
    expect(current.getIn(["en", "generic"])).toBeDefined();
    expect(current.getIn(["en", "generic"]).toJS()).toMatchObject(successData.data);
  });

  it("should not fetch translations again", async () => {
    mockedAxios.get.mockResolvedValueOnce({ ...successData });
    expect(store.getState().translations.getIn(["en", "generic"])).toBeUndefined();

    await dispatch(fetchTranslations({ domain: "generic", language: "en" }));
    const current = store.getState().translations;
    console.log(store.getState().translations.toJS());

    expect(axios.get as jest.Mock).toHaveBeenCalled();
    expect(current.getIn(["en", "generic"])).toBeDefined();
    expect(current.getIn(["en", "generic"]).toJS()).toMatchObject(successData.data);

    const secondFetch = await dispatch(fetchTranslations({ domain: "generic", language: "en" }));
    console.log(secondFetch);
    expect(secondFetch).toBeNull();
  });

  it("should dispatch failure on error", async () => {
    mockedAxios.get.mockResolvedValueOnce({ ...failData });

    const result = await dispatch(fetchTranslations({ domain: "generic", language: "en" }));

    expect((result as any).type).toBe(FETCH_TRANSLATIONS_FAIL);
  });
});

Now, first test, should properly fetch translations, works. Other two are failing. But, when I run then separately, they all work.

Also, as you can see, in the first two I have placed console.log. First one has proper values, second – default ones, just like the fetch never happened. What can I do?

Aucun commentaire:

Enregistrer un commentaire