如何在 react 中使用 axios 开玩笑测试异步操作? - 第2部分

时间:2021-01-23 08:44:09

标签: reactjs testing jestjs

这是我的previous question的延续。

我尝试测试 REGISTER_FAIL 案例。这就是我所做的:

test("should not register a  user", async () => {
  axios.mockRejectedValue({
    status: 500,
  });
  const userInfo = {
    name: "",
    email: "",
    password: "",
  };
  await store.dispatch(register(userInfo)).then(() => {
    expect(store.getActions()[0]).toEqual({
      type: REGISTER_FAIL,
      payload: {
        token: null,
        isAuthenticated: false,
        loading: true,
        // user: null,
      },
    });
  });
});

我收到此错误: enter image description here

2 个答案:

答案 0 :(得分:1)

如果您使用的是 Async/Await,则无需使用 then()

我猜如果注册失败,它会抛出一个错误。所以把测试代码放在错误捕捉部分。

test("should not register a  user", async () => {
  axios.mockRejectedValue({
    status: 500,
  });
  const userInfo = {
    name: "",
    email: "",
    password: "",
  };
  try {
    const res = await store.dispatch(register(userInfo))
  } catch (error) {
    expect(store.getActions()[0]).toEqual({
      type: REGISTER_FAIL,
      payload: {
        token: null,
        isAuthenticated: false,
        loading: true,
        // user: null,
      },
    });
  }
});

答案 1 :(得分:1)

我猜测是使用共享的 store 导致了问题的出现。我建议为每个测试单独存储。思路如下:

/** mock-store */
const createMockStore = configureMockStore([thunk]);

// Create a store maker to create store for each test
const storeMaker = () => {
  const defaultState = [];
  const store = createMockStore(defaultState);

  return store;
}

/** reset mock */
afterEach(() => jest.resetAllMocks());

test("should register a user ", async () => {
  // Run to create at each test
  const store = storeMaker();

  axios.mockImplementation(() => {
    return Promise.resolve({
      status: 200,
      data: {
        token: "testToken",
      },
    });
  });
  
  // const res = await axios.post("/api/users");
  // console.log(res.body);

  const testUser = {
    name: "testName",
    email: "test@email.com",
    password: "testPassword",
  };
  await store.dispatch(register(testUser)).then(() => {
    expect(store.getActions()[0]).toEqual({
      type: REGISTER_SUCCESS,
      payload: {
        token: "testToken",
        isAuthenticated: true,
        loading: false,
      },
    });
  });
});

test("should not register a  user", async () => {
  // Likewise above
  const store = storeMaker();

  axios.mockRejectedValue({
    status: 500,
  });
  const userInfo = {
    name: "",
    email: "",
    password: "",
  };
  await store.dispatch(register(userInfo)).then(() => {
    expect(store.getActions()[0]).toEqual({
      type: REGISTER_FAIL,
      payload: {
        token: null,
        isAuthenticated: false,
        loading: true,
        // user: null,
      },
    });
  });
});