我正在为我的异步操作编写测试。我已将我的 axios 调用抽象为一个单独的类。如果我想测试我的异步 redux 操作,我该如何编写一个模拟api.js
以便sampleAction.test.js
通过?谢谢!
api.js:
import axios from 'axios';
let apiUrl = '/api/';
if (process.env.NODE_ENV === 'test') {
apiUrl = 'http://localhost:8080/api/';
}
export default class Api {
static async get(url) {
const response = await axios.get(`${apiUrl}${url}`, {withCredentials: true});
return response;
}
}
sampleAction.js: 从 './api' 导入 Api;
export const fetchData = () => async (dispatch) => {
try {
const response = await Api.get('foo');
dispatch({
type: 'RECEIVE_DATA',
data: response.data.data,
});
} catch (error) {
handleError(error);
}
};
sampleAction.test.js:
import store from './store';
test('testing RECEIVE_DATA async action', () => {
const expectedActions = [
{ type: 'RECEIVE_DATA', data: 'payload' },
];
return store.dispatch(actions.fetchData()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});