【问题标题】:how to jest test an async action with axios in react ? - part 2如何在反应中用 axios 开玩笑地测试异步操作? - 第2部分
【发布时间】:2021-04-27 15:16:22
【问题描述】:

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

我收到此错误:

【问题讨论】:

    标签: reactjs testing jestjs


    【解决方案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,
          },
        });
      });
    });
    

    【讨论】:

    • 刚刚想通了。或者我可能只是更改了 store.getActions() 的索引号,即 expect(store.getActions()[1]).toEqual({ type: REGISTER_FAIL, payload: { token: null, isAuthenticated: false, loading: true, }, });
    • 可以,但最好分开测试。假设您删除了一项测试或更改顺序会再次产生问题
    【解决方案2】:

    如果您使用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,
          },
        });
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 2018-02-22
      • 1970-01-01
      相关资源
      最近更新 更多