如何开玩笑地用axios测试异步动作? - 第2部分 [英] how to jest test an async action with axios in react ? - part 2

查看:98
本文介绍了如何开玩笑地用axios测试异步动作? - 第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我我尝试测试REGISTER_FAIL情况.这就是我所做的:

I tried testing for REGISTER_FAIL case. This is what i did:

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

我收到此错误:

推荐答案

我猜是由于使用共享的store导致了问题的出现.我建议为每个测试分开存储.这个想法如下所示:

I'm guessing the issue from using the shared store which ended up the issue. I would suggest to separate store for each test. The idea looks like below:

/** 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,
      },
    });
  });
});

这篇关于如何开玩笑地用axios测试异步动作? - 第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆