how to jest test an async action with axios in react ? - part 2

Viewed 143

This is a continuation of my previous question.

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

I am getting this error: enter image description here

2 Answers

If you are using Async/Await, then no need to use then()

I guess if the register failed, it would throw an error. So put the test code in error catching part.

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

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