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

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

问题描述

我有一个动作生成器register.js:

I have an action-generator register.js:

import { REGISTER_SUCCESS, REGISTER_FAIL } from "./types";
import axios from "axios";

export const register = (formData) => async (dispatch) => {
  const { name, email, password } = formData;
  const configRegister = {
    method: "post",
    url: "/api/users",
    headers: { "Content-Type": "application/json" },
    data: { name, email, password },
  };
  try {
    const res = await axios(configRegister);
    const token = res.data.token;
    dispatch({
      type: REGISTER_SUCCESS,
      payload: {
        token,
        isAuthenticated: true,
        loading: false,
      },
    });
  } catch (err) {
    console.error(err);
    dispatch({
      type: REGISTER_FAIL,
      payload: {
        token: null,
        isAuthenticated: false,
        loading: true,
      },
    });
  }
}; 

端点/api/users成功返​​回{token:'a_token_string'}.

我应该如何使用玩笑来测试此动作生成器?

我尝试这样做,register.test.js:-

I tried doing this, register.test.js :-

import {
  REGISTER_SUCCESS,
} from "./types";
import thunk from "redux-thunk";
import configureMockStore from "redux-mock-store";
import axios from "axios";

jest.mock("axios");
    
/** mock-store */
const createMockStore = configureMockStore([thunk]);
const defaultState = [];
const store = createMockStore(defaultState);
/** reset mock */
afterEach(() => jest.resetAllMocks());

test("should register a  user ", async () => {
  axios.post.mockImplementation(() => {
    return Promise.resolve({
      status: 200,
      body: {
        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,
      },
    });
  });
});

推荐答案

您已经很接近完成它了.问题是,您的实现直接从axios对象使用时,您正在模拟axios.post.只要模拟axios对象,它就可以正常工作.这是建议的更改,请检查内联注释以了解您还应该更改的内容:

You're quite close to get it done. The thing is you're mocking axios.post while your implementation is using directly from axios object. As long as you mock axios object then it would work as it should. Here is proposed changes, please check inline comments for things you should also change:

test("should register a user ", async () => {
  // Mock `axios` object directly
  axios.mockImplementation(() => {
    return Promise.resolve({
      status: 200,
      // should also change from `body` to `data` as well
      data: {
        token: "testToken",
      },
    });
  });
  
  // it will no longer work since the mock is changed
  // 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,
      },
    });
  });
});

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

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