在React组件开玩笑测试中模拟Axios实例和拦截器

问题描述

我正在测试一个调用API以用数据填充表的组件。尽管使用了axios,但在通过拦截器执行请求之前,将axios包裹在一种方便的方法中,以填充标头。我已经尝试过axios-mock-adapter,但是没有用。我对测试React还是很陌生,但我对如何模拟从api / axios返回的数据一无所知。我该如何模拟api调用来模拟要通过的数据?

这是我的简单测试:

test('<EmailTable/> ',async () => {
  const { debug,getByText } = render(<CommunicationEmail />);
  await waitFor(() => expect(getByText('Test Email Subject')).toBeTruthy());
}

这是axios包装器(api.js):

const instance = axios.create({
  baseURL: `${apiUrl}/v1`,timeout: 12000,withCredentials: true,headers: headers,});

//intercept requests to validate hashed auth token
instance.interceptors.request.use((request) => {
  const token = request.headers['X-Our-Access-Token'];
  if (
    localStorage.getItem('user_token') == null ||
    SHA256(token).toString(enc.Hex) == localStorage.getItem('user_token')
  ) {
    return request;
  } else {
    console.log({ what: 'Auth key invalid' });
    return Promise.reject('Invalid token!');
  }
});

//intercept responses to handle 401 errors
instance.interceptors.response.use(
  (response) => {
    return response;
  },(error) => {
    // handle 401 authentication errors and redirect to SSO
    if (error.response != null && error.response.status != null && error.response.status === 401) {
      console.error({ what: 'Authorization error',e: error });
    }
    return Promise.reject(error);
  }
);

export default instance;

这是我要测试的组件的简化:

import api from './api.js';

const EmailTable = () => {
   const [emails,setEmails] = useState();

   useEffect(() => {
      if(!emails) {
         getEmails();
      }
   },[emails]);

   const getEmails = async () => { 
      await api({
        method: 'GET',url: `/communications/emails`,}).then((response) => {
        if (response.success) {
           setEmails(response.emails);
        }
      }
    }

   if(!emails) { return <div> Loading... </div> }; 
   return <div>{emails}</div>;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...