我不熟悉使用Jest进行测试,并且一直坚持如何测试这段代码,以证明在调用我的registerUser时已调用Axios.post。我已经在网上搜索过,还没有可靠的解决方案。如果能提供解决方案,将不胜感激
这是我需要从authAction.js测试的功能
library(parallel)
c4 <- parallel::makeCluster(4)
df1_split <- split(df1_sf, cut(1:nrow(df1_sf), 4, labels = FALSE))
clusterExport(c2, "df2_sf")
clusterEvalQ(c2, library(RANN))
system.time(
idxlist_parallel <- clusterApply(c2, df1_split,
function(x) nn2(df2_sf, x, k = 1, treetype = 'bd', searchtype = 'priority'))
)
我已经尝试过了,但是似乎没有用。
export const registerUser = (userData, history) => dispatch => {
axios
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
谢谢。
答案 0 :(得分:1)
从如下函数返回Promise
:
export const registerUser = (userData, history) => dispatch => {
return axios // <= return the Promise
.post("/api/users/register", userData)
.then(res => history.push("/login")) // re-direct to login on successful register
.catch(err =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
...然后您可以像这样测试它:
import * as authActions from './authActions';
import axios from 'axios';
describe('registerUser', () => {
let mock;
beforeEach(() => {
mock = jest.spyOn(axios, 'post');
});
afterEach(() => {
mock.mockRestore();
});
it('should register the user and redirect to login', async () => {
const push = jest.fn();
const history = { push };
const dispatch = jest.fn();
mock.mockResolvedValue(); // mock axios.post to resolve
await authActions.registerUser('the user data', history)(dispatch);
expect(mock).toHaveBeenCalledWith('/api/users/register', 'the user data'); // Success!
expect(history.push).toHaveBeenCalledWith('/login'); // Success!
});
});
答案 1 :(得分:-1)
export const addOrganizationsData = (params) => (dispatch) => {
dispatch(showSpinner());
return interceptor
.post(`/api/v1/organizations`, params)
.then(({ data }) => {
dispatch(actionTypes.saveOrganization(data));
dispatch(closeSpinner());
})
.catch((err) => {
dispatch(actionTypes.organizationsError(err));
dispatch(closeSpinner());
});
};