开玩笑在两个异步测试中失败,在每个异步测试中成功

时间:2019-05-02 06:33:20

标签: testing async-await jestjs

我的考试有一个奇怪的问题。我有一个运行几个异步it的套件。看起来像这样:

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);
  });
});

现在,第一个测试should properly fetch translations有效。另外两个都失败了。但是,当我分开跑步时,它们都起作用。

此外,如您所见,在前两个中,我放置了console.log。第一个具有适当的值,第二个-具有默认值,就像从未发生过提取一样。我该怎么办?

0 个答案:

没有答案